Is it possible to rename multiple list names in a list?

Viewed 133

I want to rename my list names in a list.

For example:

library(randNames) #using this package for the random names for the example
my_info <- rand_names(10)
my_second_info <- rand_names(10)

list1 <- list(A = c(my_info$name.first), B = c(rnorm(1:10)), C = c(rnorm(1:10)), D = c(rnorm(1:10)))
list2 <- list(A = c(my_second_info$name.first), B = c(rnorm(1:10)), C = c(rnorm(1:10)), D = c(rnorm(1:10)))

both_lists <- list(list1,list2)

And now when I call both_lists I get [[1]] as a name for the first list and [[2]] as a name of the second list (as depicted here).

I would like to change the name of list1 and list2 (and for all others that may be added to it), to the first name random name. So list 1 would be named the both_lists[[1]]$A[1] and list 2 would be named to both_lists[[2]]$A[1].

Is this possible? Or does the list name get lost for example when making a list of lists and it just becomes a specific number?

3 Answers

You can use sapply to extract 1st value from A sublist in all the lists and assign it as name.

names(both_lists) <- sapply(both_lists, function(x) x$A[1])

You can do this using names()

names(both_lists) <- c(both_lists[[1]]$A[1],both_lists[[2]]$A[1])

You may use setNames by the values you get in the first row when you use unlist in an sapply.

both_lists <- setNames(both_lists, sapply(both_lists, unlist)[1,])

names(both_lists)
# [1] "Vilma" "Naomi"

Data: I used your code with set.seed(42).

Related