lowndrul
lowndrul

Reputation: 3815

Set all vector elements to NA in a list of vectors

How can I set all vector elements to NA in a list of vectors?

Essentially, I'd like to keep an existing list's structure and names but empty all values, to fill them in later. I provide a minimal example with a couple solutions below. I prefer base and tidyverse (esp. purrr) solutions, but can get on board with any approach which is better than what I have below.

my_list <- list(A = c('a' = 1, 'b' = 2, 'c' = 3), B = c('x' = 10, 'y' = 20))
ret_list <- my_list

# Approach 1
for (element_name in names(my_list)) {
  ret_list[[element_name]][] <- NA
}

ret_list
# $A
# a  b  c 
# NA NA NA 
# 
# $B
# x  y 
# NA NA 

# Approach 2    
lapply(my_list, function(x) {x[] <- NA; return(x)})
# $A
# a  b  c 
# NA NA NA 
# 
# $B
# x  y 
# NA NA 

Upvotes: 9

Views: 1799

Answers (5)

Julius Vainora
Julius Vainora

Reputation: 48211

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)

Upvotes: 8

G. Grothendieck
G. Grothendieck

Reputation: 269526

If the list is not restricted to one level then use rapply.

# test data modified from question
my_list2 <- list(list(A = c(a = 1, b = 2, c = 3)), B = c(x = 10, y = 20))

rapply(my_list2, function(x) replace(x, TRUE, NA), how = "list")

which can also be written as:

rapply(my_list2, replace, list = TRUE, values = NA, how = "list")

Upvotes: 4

Mankind_2000
Mankind_2000

Reputation: 2208

another alternative with dplyr:

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

Upvotes: 4

989
989

Reputation: 12937

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 

Upvotes: 4

Rui Barradas
Rui Barradas

Reputation: 76402

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 

Upvotes: 8

Related Questions