assign identical list to vector of names r in r

To assign identical lists to a vector of names in R, we can use the list() function to create the list and the setNames() function to assign the list to the names vector.

Here is an example code:

# create an example list
example_list <- list(a = 1, b = 2, c = 3)

# create a vector of names
names_vec <- c("d", "e", "f")

# assign the identical list to the names vector
result <- setNames(replicate(length(names_vec), example_list, simplify = FALSE), names_vec)
266 chars
9 lines

In this code, we first create an example list with three elements "a", "b", and "c". Then, we create a vector of names "d", "e", and "f". We use the replicate() function to create a list of the same length as names_vec, with each element being the example_list. The setNames() function assigns this list to the names_vec.

The result will be a named list with three elements "d", "e", and "f", each of which is identical to the example_list.

gistlibby LogSnag