Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set all vector elements to NA in a list of vectors

Tags:

r

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 
like image 921
lowndrul Avatar asked Dec 31 '18 22:12

lowndrul


People also ask

Is it possible to create a list of vectors?

The lists comprising of vectors can be merged together to form a larger list. The lists are merged in the order in which they appear in the function as arguments. The total size of the merged list is the sum of sizes of individual lists.

How do you replace all values in a vector?

The replacement of values in a vector with the values in the same vector can be done with the help of replace function. The replace function will use the index of the value that needs to be replaced and the index of the value that needs to be placed but the output will be the value in the vector.

How do I make a list of numbers into a vector?

To convert List to Vector in R, use the unlist() function. The unlist() function simplifies to produce a vector by preserving all atomic components.

How do I change an element to a vector in R?

Replace the Elements of a Vector in R Programming – replace() Function. replace() function in R Language is used to replace the values in the specified string vector x with indices given in list by those given in values.


1 Answers

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 
like image 58
989 Avatar answered Oct 19 '22 19:10

989