[R] replace elements in a list

Wincent ronggui.huang at gmail.com
Fri Apr 30 06:40:26 CEST 2010


On 30 April 2010 12:14, Erik Iverson <eriki at ccbr.umn.edu> wrote:
> 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?
> Note:
> 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

Yes, it is a list of lists. I realized the returned value might have
NULL after I have the data. I just need to deal with it.
You are right, when I knew that, I will generate NA in the first place.

> Solution 2:
> lapply(l, function(x) lapply(x, function(x) ifelse(is.null(x), NA, x)))

Cool. that is what I want.

Thanks gain.

Wincent Rong-gui HUANG
Doctoral Candidate
Dept of Public and Social Administration
City University of Hong Kong

More information about the R-help mailing list