[R] replace elements in a list

Erik Iverson eriki at ccbr.umn.edu
Fri Apr 30 06:14:09 CEST 2010

Wincent wrote:
> Dear all, I have a list like this:  l <- list(list(a=1,b=NULL), list(a=2,b=2))
> I want to find out the elements with value of NULL and replace them with NA.
> The actual case has a very long list, so manually find out and replace
> them is not an option.
> I can use for loop to do this, but I want to know if there is
> vectorized way (or other ways) to do it?

You have provided a list *of lists*.  Is that what you actually have?  If so,

Solution 1:

Change whatever is generating the NULL values to NA in the first place

Solution 2:

lapply(l, function(x) lapply(x, function(x) ifelse(is.null(x), NA, x)))

More information about the R-help mailing list