Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent unlist to drop NULL values

Tags:

list

null

r

I have a vector of lists and I use unlist on them. Some of the elements in the vectors are NULL and unlist seems to be dropping them.

How can I prevent this?

Here's a simple (non) working example showing this unwanted feature of unlist

a = c(list("p1"=2, "p2"=5),        list("p1"=3, "p2"=4),        list("p1"=NULL, "p2"=NULL),        list("p1"=4, "p2"=5)) unlist(a)  p1 p2 p1 p2 p1 p2   2  5  3  4  4  5  
like image 946
nico Avatar asked Jun 07 '10 17:06

nico


1 Answers

In this case (one level depth list) this should works too:

a[sapply(a, is.null)] <- NA unlist(a) # p1 p2 p1 p2 p1 p2 p1 p2  #  2  5  3  4 NA NA  4  5 
like image 147
Marek Avatar answered Oct 07 '22 19:10

Marek