Unlist a list without losing NULL's

Viewed 797

I have a function that takes a character vector as input and returns inconsistent results. If there are no NA's in the input, it will return a named vector of "translated" values. If there are NA's in the input, it will return a list. The element of the list corresponding to NA will be NULL with the name NA.

Here is such a list recreated:

foo <- list(a=1, b=2, c=NULL)
names(foo) <- c("a", "b", NA)

What I would want to have is a vector with NA's in the missing values:

c(1, 2, NA)

However, a simple unlist() does not work – the NULL element disappear. I tried the following:

foo <- lapply(foo, function(x) if(is.null(x)) NA else x)
names(foo) <- NULL
unlist(foo)

This works. However, foo is quite large (tens of thousands of elements) and it appears that the above code is rather slow. Is there a better solution?

2 Answers

NULL has length of 0, so we can use that :

foo[lengths(foo) == 0] <- NA
unlist(foo, use.names = FALSE)
#[1]  1  2 NA

One option could be:

foo[sapply(foo, is.null)] <- NA
unlist(foo, use.names = FALSE)

[1]  1  2 NA
Related