Home > Back-end >  Use purrr::map*() to assign a nested list element to another nested list
Use purrr::map*() to assign a nested list element to another nested list

Time:10-29

I have two lists:

listA <- list(group1 = tibble(names = LETTERS[1:5],
                              names_num = 1:5),
              group2 = tibble(names = LETTERS[11:13],
                              names_num = 1:3))
  
listB <- list(group1 = list(labels = NULL,
                            order = 5:1),
              group2 = list(labels = NULL,
                            order = 3:1))

My goal is to modify listB$groupX$labels by inserting the names vector from listA for each group, and in the order specified by listB$groupX$order. The desired output would look like this:

> listB_mod
$group1
$group1$labels
[1] "E" "D" "C" "B" "A"
$group1$order
[1] 5 4 3 2 1

$group2
$group2$labels
[1] "M" "L" "K"
$group2$order
[1] 3 2 1

Is there a way to achieve this, preferably using the purrr::map() family?

Any hints much appreciated!

CodePudding user response:

Most of the logic is unrelated to ‘purrr’ functionality but of course you can use map2 to apply the logic to all pairwise items in the two lists:

listB_mod = map2(
    listA, listB,
    ~ list(labels = .x$names[match(.x$names_num, .y$order)], order = .y$order)
)
  • Related