Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Merge and overwrite list elements

Thanks in advance for any help with this.

I have a function where users can pass in arguments to a list() with .... I am looking for a way to overwrite obj_a with all values that exist in obj_b.

Here’s a reprex:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

# i have a default object in a function, and users can pass in ...
obj_1 <- list(apple = "green",
              list(apple = "green", donut = "glazed"))

# ... is stored as obj_2
obj_2 <- list(apple = "red")

# obj_2 could also be
obj_2 <- list(apple = "red", donut = "sprinkle")


modifyList(obj_1, obj_2)
#> $apple
#> [1] "red"
#> 
#> [[2]]
#> [[2]]$apple
#> [1] "green"
#> 
#> [[2]]$donut
#> [1] "glazed"
#> 
#> 
#> $donut
#> [1] "sprinkle"

The desired outcome would be:

#> $apple
#> [1] "red"
#> 
#> [[2]]
#> [[2]]$apple
#> [1] "red"
#> 
#> [[2]]$donut
#> [1] "sprinkle"
#> 
#> 
#> $donut
#> [1] "sprinkle"

>Solution :

Some recursion should work here:

func <- function(L1, L2) {
  L1 <- modifyList(L1, L2)
  islst <- sapply(L1, is.list)
  L1[islst] <- lapply(L1[islst], modifyList, L2)
  L1
}

obj_1 <- list(apple = "green",
              list(apple = "green", donut = "glazed"))
obj_2 <- list(apple = "red")
func(obj_1, obj_2)
# $apple
# [1] "red"
# [[2]]
# [[2]]$apple
# [1] "red"
# [[2]]$donut
# [1] "glazed"

obj_2 <- list(apple = "red", donut = "sprinkle")
func(obj_1, obj_2)
# $apple
# [1] "red"
# [[2]]
# [[2]]$apple
# [1] "red"
# [[2]]$donut
# [1] "sprinkle"
# $donut
# [1] "sprinkle"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading