Home > front end >  How to name objects in many lists at once in R?
How to name objects in many lists at once in R?

Time:11-06

I've got three lists with and each of them contains many tibbles. I want to name objects within the lists based on a particular value in the tibble. I know how to do it with one list at a time. To make things easier, I'll use vectors in my example:

library("purrr")

list1 <- list(c(id = "ABC", val=1), c(id = "DEF", val = 2), c(id = "GHI", val = 3))
list2 <- list(c(id = "JKL", val=4), c(id = "MNO", val = 5), c(id = "PRS", val = 6))
list3 <- list(c(id = "TUW", val=7), c(id = "XYZ", val = 8), c(id = "ZYX", val = 8))

names(list1) <- map_chr(list1, ~ .x[["id"]])
names(list2) <- map_chr(list2, ~ .x[["id"]])
names(list3) <- map_chr(list3, ~ .x[["id"]])

It works but I wonder if there's any bulk method of getting it done. I've tried using a for loop, but it didn't work, it creates separate i variable but doesn't rename objects in my lists:

for (i in c(list1, list2, list3)) {names(i) <- map_chr(i, ~ .x[["id"]])}

I know for loops are considered a bad practice in R so other suggestions would be much appreciated.

CodePudding user response:

One way to approach this is to combine your lists first, so that the combined lists will have their names changed

list_of_lists <- list(list1, list2, list3)

list_of_lists <- 
  lapply(list_of_lists, function(y) setNames(y, map_chr(y, ~ .x[["id"]])))

[[1]]
[[1]]$ABC
   id   val 
"ABC"   "1" 

[[1]]$DEF
   id   val 
"DEF"   "2" 

[[1]]$GHI
   id   val 
"GHI"   "3" 


[[2]]
[[2]]$JKL
   id   val 
"JKL"   "4" 

[[2]]$MNO
   id   val 
"MNO"   "5" 

[[2]]$PRS
   id   val 
"PRS"   "6" 


[[3]]
[[3]]$TUW
   id   val 
"TUW"   "7" 

[[3]]$XYZ
   id   val 
"XYZ"   "8" 

[[3]]$ZYX
   id   val 
"ZYX"   "8" 

CodePudding user response:

In the for loop, we may need assign

for(nm in paste0('list', 1:3)) {
    tmp <- get(nm)
    names(tmp) <- sapply(tmp, function(x) x[["id"]])
     assign(nm, tmp)
}

-output

> list1
$ABC
   id   val 
"ABC"   "1" 

$DEF
   id   val 
"DEF"   "2" 

$GHI
   id   val 
"GHI"   "3" 
  • Related