Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace values in list

Tags:

r

I have a nested list, which could look something like this:

characlist<-list(list(c(1,2,3,4)),c(1,3,2,NA))

Next, I want to replace all values equal to one with NA. I tried the following, but it produces an error:

lapply(characlist,function(x) ifelse(x==1,NA,x))

Error in ifelse(x == 1, NA, x) : 
  (list) object cannot be coerced to type 'double' 

Can someone tell me what's wrong with the code?

like image 257
STATEN_star Avatar asked Feb 09 '16 13:02

STATEN_star


2 Answers

Use rapply instead:

> rapply(characlist,function(x) ifelse(x==1,NA,x), how = "replace")
#[[1]]
#[[1]][[1]]
#[1] NA  2  3  4
#
#
#[[2]]
#[1] NA  3  2 NA

The problem in your initial approach was that your first list element is itself a list. Hence you cannot directly apply the ifelse logic as you would on an atomic vector. By using ?rapply you can avoid that problem (rapply is a recursive version of lapply).

like image 90
talat Avatar answered Oct 25 '22 14:10

talat


Another option would be using relist after we replace the elements that are 1 to NA in the unlisted vector. We specify the skeleton as the original list to get the same structure.

 v1 <- unlist(characlist)
 relist(replace(v1, v1==1, NA), skeleton=characlist)
 #[[1]]
 #[[1]][[1]]
 #[1] NA  2  3  4


 #[[2]]
 #[1] NA  3  2 NA
like image 32
akrun Avatar answered Oct 25 '22 13:10

akrun