# Set all vector elements to NA in a list of vectors

• A+
Category：Languages

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  ``

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