12

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?

0

2 Answers 2

20

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).

Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.