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
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.
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.
To convert List to Vector in R, use the unlist() function. The unlist() function simplifies to produce a vector by preserving all atomic components.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With