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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With