translating for loop in map2

Hello everyone,

Bellow are 2 list which i want to manipulate. The first list, list1, contains three elements with random numbers. The second one is pretty much the same but it has one layer more on top of it (lev).

list1 <- list(
  elem1 = list(runif(2)), 
  elem2 = list(runif(2)), 
  elem3 = list(runif(2))  
)

list2 <- list(
  lev1 = list(
    elem1 = list(sample(letters, 2)), 
    elem2 = list(sample(letters, 2)), 
    elem3 = list(sample(letters, 2))  
  ),
  lev2 = list(
    elem1 = list(sample(letters, 2)), 
    elem2 = list(sample(letters, 2)), 
    elem3 = list(sample(letters, 2))  
  )
)

The goal is to "transfer" information from list2 for each elem into list1 while keeping track of lev layer and encoding it as name.
Bellow is the for loop that works, what would be the purrr equivalents?

 for (lev in names(list2)) {
  for(elem in names(list2[[lev]])) {
    new_name <- paste(lev, elem, sep = "_")
    list1[[elem]][[new_name]] <- list2[[lev]][[elem]]
  }
}

Thank you for the help

I came up with this;
the forloop is probably better in this case.


list1 <- list(
  elem1 = list(runif(2)), 
  elem2 = list(runif(2)), 
  elem3 = list(runif(2))  
)
list1_orig <- list1

list2 <- list(
  lev1 = list(
    elem1 = list(sample(letters, 2)), 
    elem2 = list(sample(letters, 2)), 
    elem3 = list(sample(letters, 2))  
  ),
  lev2 = list(
    elem1 = list(sample(letters, 2)), 
    elem2 = list(sample(letters, 2)), 
    elem3 = list(sample(letters, 2))  
  )
)

#original code
for (lev in names(list2)) {
  for (elem in names(list2[[lev]])) {
    new_name <- paste(lev, elem, sep = "_")
    list1[[elem]][[new_name]] <- list2[[lev]][[elem]]
  }
}

#adapted code
library(purrr)

f2 <- (list_flatten(list2))
nf2 <- names(f2)
 
l3 <- imap(list1_orig, \(x, y){
  nms <- nf2[endsWith(nf2, y)]
  c(x, set_names(map(nms, \(fx){
    f2[[fx]]
  }), nms))
})

waldo::compare(list1,l3)
# identical
1 Like

Tank you, @nirgrahamuk!

I was also having an impression that a for loop is more reasonable in this situation. I would say the way to go in this situation is to align the lists better. Can you perhaps points towards resources where this kind of restructuring is required for better flow, if any resources of that kind exist.

Regards

Sorry I'm not aware of any such resources.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.