Assign values with same name in a nested list in R

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Assign values with same name in a nested list in R



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:


e1


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.


modify_depth()


purrr



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.


ls2


for



Thanks for your help!









By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

make 2 or more post in bootsrap

Store custom data using WC_Cart add_to_cart() method in Woocommerce 3

Firebase Auth - with Email and Password - Check user already registered