Home > other >  Merge and overwrite list elements
Merge and overwrite list elements

Time:03-19

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:

# 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"

CodePudding user response:

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"
  • Related