[R] replace elements in a list

William Dunlap wdunlap at tibco.com
Fri Apr 30 17:14:02 CEST 2010


> -----Original Message-----
> From: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] On Behalf Of Wincent
> Sent: Thursday, April 29, 2010 8:40 PM
> To: r help
> Subject: [R] replace elements in a list
> 
> 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.

I think that rapply(how="replace") ought to be able to do this
but it doesn't do the right thing when the list has a NULL in
it.  E.g., see how the following returns a list the shape of
the input list, changing all the non-NULL entries as requested,
but the NULL entries are replaced by empty lists instead of 0's:
  > rapply(l, function(x)
  +   if(is.null(x)) 0 else paste("*", deparse(x), "*", collapse="/",
sep=""),  how="replace")
  [[1]]
  [[1]]$a
  [1] "*1*"

  [[1]]$b
  list()
  
  
  [[2]]
  [[2]]$a
  [1] "*2*"

  [[2]]$b
  [1] "*2*"

The following function may do what you want:
  replaceInList <- function (x, FUN, ...) 
  {
      if (is.list(x)) {
          for (i in seq_along(x)) {
              x[i] <- list(replaceInList(x[[i]], FUN, ...))
          }
          x
      }
      else FUN(x, ...)
  }
E.g.,
  > replaceInList(l, function(x)if(is.null(x))0 else x)
  [[1]]
  [[1]]$a
  [1] 1

  [[1]]$b
  [1] 0
  
  
  [[2]]
  [[2]]$a
  [1] 2
  
  [[2]]$b
  [1] 2

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com 

> 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?
> 
> Thanks
> -- 
> Wincent Rong-gui HUANG
> Doctoral Candidate
> Dept of Public and Social Administration
> City University of Hong Kong
> http://asrr.r-forge.r-project.org/rghuang.html
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
> 



More information about the R-help mailing list