Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

r unlist function unexpected results

Tags:

r

Trying to flatten a list to a vector I've just found an unexpected behaviour. To simplify let's do what ?unlist proposes as an example:

unlist(options())

Look at the original list size:

length(unlist(options())) # 69 in my environment

Should the unlisted list retain its length? I would think so, but...

length(unlist(options())) # 79!!!
length(unlist(options(), use.names = F)) # Another 79

What is happening? I need to retain the list values but unlist() gives me an extra.

like image 400
Javi Rodríguez Avatar asked Oct 31 '22 09:10

Javi Rodríguez


1 Answers

This is because some of the list elements may have more than one value. Thus, unlist is doing exactly what it is being asked to do.

Look at the following examples:

L <- list(1, c(1, 2, 3), 1, c(4, 5))
length(L)         # 4        <<< How many list elements are there?
length(unlist(L)) # 7        <<< How many elements are there within the list?
lengths(L)        # 1 3 1 2  <<< How many elements are in each list element?
sum(lengths(L))   # 7        <<< How many elements should we expect from unlist?

If you only expected the first value for each, you can extract that alone using something like:

sapply(L, `[[`, 1)
# [1] 1 1 1 4

(Which is a vector equal to the length of the list, but has a good amount of data missing).

like image 151
A5C1D2H2I1M1N2O1R2T1 Avatar answered Nov 15 '22 07:11

A5C1D2H2I1M1N2O1R2T1