I want to assign the same value to specific elements in nested lists that have the same name. I would also like to create the element if it didn't exist in the nested list, but this isn't shown in my example.
For example, let's say I have:
ls <- list(a = list(e1 = "value1.1", e2 = "value1.2"),
b = list(e1 = "value2.1", e2 = "value2.2"))
And I want to assign the value "same value" to all the elements in sublists that are named e1 so that I would end up with this desired output:
list(a = list(e1 = "same value", e2 = "value1.2"),
b = list(e1 = "same value", e2 = "value2.2")
> ls
$a
$a$e1
[1] "same value"
$a$e2
[1] "value1.2"
$b
$b$e1
[1] "same value"
$b$e2
[1] "value2.2"
After researches, I found the function modify_depth() in the package purrr that will apply a function to the nested lists, but won't assign a value.
My only other solution was to do this:
ls2 <- list()
for(sublist in ls){
sublist[["e1"]] <- "same value"
ls2 <- c(ls2, list(sublist))
}
names(ls2) <- names(ls)
ls <- ls2
rm(ls2)
Note: after the loop, "same value" are not assigned in ls, so I have to create ls2. I could make this a function, but I'm sure there is a better way to do this, without a for loop.
Thanks for your help!