user2205916
user2205916

Reputation: 3456

Why is my unlist result shorter than my list?

Why does unlisting my list data structure result in a different length? The length of the list is 13951. The length of the unlisted result is 13654. There are no NULL's or NA's.

> class(price)
[1] "list"

> head(price)
$`570`
[1] 0

$`440`
[1] 0

$`730`
[1] 1499

$`304930`
[1] 0

$`550`
[1] 1999

$`230410`
[1] 0

length(names(price))  # 13951
length(price)         # 13951
length(unlist(price)) # 13654

> sum(is.na(price))
[1] 0
> sum(is.null(price))
[1] 0

How do I ensure the unlist length is the same as the list length?

-- ATTEMPTED SOLUTION BELOW:

> out <- do.call(c, lapply(price, (function(x) {
+   if (is.null(x)) {NA} else { x } 
+ })))
> length(out) #2
[1] 13654


> table(sapply(price, class))

numeric 
  13951 

Upvotes: 3

Views: 1836

Answers (1)

Damiano Fantini
Damiano Fantini

Reputation: 1975

One thing is to count elements in the list. Another is to count their lengths...

a.list <- list(a= 1, b= NULL, c = list())
length(a.list) # 3
sum(lengths(a.list)) # 1 {as suggested by Nicola}
# same as: sum(sapply(a.list, length)) # 1

I assume you have named list elements that are NULL (or length == 0). When you unlist, those should be lost.

length(unlist(a.list)) #1

If you want to extract something from all named elements (replacing a NULL with a NA) you could do as follows.

out <- do.call(c, lapply(a.list, (function(x) {
  if (is.null(x) | length(x) == 0) {NA} else { x } 
})))
length(out) #3

This assumes you have no 2-level lists.

Upvotes: 7

Related Questions