Home > Software design >  R - set names of nested list elements according to values in another nested list
R - set names of nested list elements according to values in another nested list

Time:11-13

Let's say that we have two nested lists with the equal number of levels:

list1 <- list(list("a", "b"),
              list("c", "d"))

list2 <- list(list("e", "f"),
              list("g", "h"))

Now I want to set the names of the elements of the sublist of list1 according to the values of list2. The desired output would be equivalent to using this:

list1 <- list(list(e = "a", 
                   f = "b"),
              list(g = "c", 
                   h = "d"))

However, I need a way to not do it manually and to instead pull the values from list2 and assign them as names to the appropriate list level of list1.

CodePudding user response:

Base R: Use setNames() within lapply():

list1 <- lapply(
  seq_along(list1),
  \(i) setNames(list1[[i]], list2[[i]])
)

tidyverse: Use purrr::map2() to loop over both lists simultaneously:

library(purrr)

list1 <- map2(list1, list2, set_names)

Output in both cases:

[[1]]
[[1]]$e
[1] "a"

[[1]]$f
[1] "b"


[[2]]
[[2]]$g
[1] "c"

[[2]]$h
[1] "d"
  •  Tags:  
  • r
  • Related