Set all vector elements to NA in a list of vectors

another alternative with dplyr:

lapply(my_list, function(x) dplyr::na_if(x,x))

Another way around

relist(replace( unlist(my_list), TRUE, NA ), skeleton = my_list)

#$A
# a  b  c 
#NA NA NA 

#$B
# x  y 
#NA NA 

You can use function is.na<- in a lapply loop.

ret_list <- lapply(my_list, `is.na<-`)
ret_list
#$A
# a  b  c 
#NA NA NA 
#
#$B
# x  y 
#NA NA 

Here's another one for numeric vectors:

lapply(my_list, `*`, NA) # Instead of * it could also be +, -, etc.
# $A
#  a  b  c 
# NA NA NA 
#
# $B
#  x  y 
# NA NA 

More generally,

lapply(my_list, replace, TRUE, NA)

and

lapply(ret_list, ifelse, NA, NA)

Tags:

R