list_modify() recursively modifies a list, matching elements either by name or position. list_update() is a helper optimised for interactively modifying an existing list: you can use a formula (a quosure) to replace using existing values.

list_modify(x, y)

list_update(`_x`, ...)

Arguments

y

Replacement list

_x, x

List to modify

...

New values of a list. Use NULL to remove values. Use a formula to evaluate in the context of the list values.

Examples

x <- list(x = 1:10, y = 4, z = list(a = 1, b = 2)) str(x)
#> List of 3 #> $ x: int [1:10] 1 2 3 4 5 6 7 8 9 10 #> $ y: num 4 #> $ z:List of 2 #> ..$ a: num 1 #> ..$ b: num 2
# Update values str(list_modify(x, list(a = 1)))
#> List of 4 #> $ x: int [1:10] 1 2 3 4 5 6 7 8 9 10 #> $ y: num 4 #> $ z:List of 2 #> ..$ a: num 1 #> ..$ b: num 2 #> $ a: num 1
# Replace values str(list_modify(x, list(z = 5)))
#> List of 3 #> $ x: int [1:10] 1 2 3 4 5 6 7 8 9 10 #> $ y: num 4 #> $ z: num 5
str(list_modify(x, list(z = list(a = 1:5))))
#> List of 3 #> $ x: int [1:10] 1 2 3 4 5 6 7 8 9 10 #> $ y: num 4 #> $ z:List of 2 #> ..$ a: int [1:5] 1 2 3 4 5 #> ..$ b: num 2
# Remove values str(list_modify(x, list(z = NULL)))
#> List of 2 #> $ x: int [1:10] 1 2 3 4 5 6 7 8 9 10 #> $ y: num 4
# list_update is useful for interactive tweaking, because it # uses ... instead of a separate list str(list_update(x, a = 1))
#> List of 4 #> $ x: int [1:10] 1 2 3 4 5 6 7 8 9 10 #> $ y: num 4 #> $ z:List of 2 #> ..$ a: num 1 #> ..$ b: num 2 #> $ a: num 1
str(list_update(x, z = 5))
#> List of 3 #> $ x: int [1:10] 1 2 3 4 5 6 7 8 9 10 #> $ y: num 4 #> $ z: num 5
str(list_update(x, z = list(a = 1:5)))
#> List of 3 #> $ x: int [1:10] 1 2 3 4 5 6 7 8 9 10 #> $ y: num 4 #> $ z:List of 2 #> ..$ a: int [1:5] 1 2 3 4 5 #> ..$ b: num 2
str(list_update(x, z = NULL))
#> List of 2 #> $ x: int [1:10] 1 2 3 4 5 6 7 8 9 10 #> $ y: num 4
# In list_update() you can also use formulas to compute new values list_update(x, z1 = ~ z[1])
#> $x #> [1] 1 2 3 4 5 6 7 8 9 10 #> #> $y #> [1] 4 #> #> $z #> $z$a #> [1] 1 #> #> $z$b #> [1] 2 #> #> #> $z1 #> $z1$a #> [1] 1 #> #>
list_update(x, z = ~ x + y)
#> $x #> [1] 1 2 3 4 5 6 7 8 9 10 #> #> $y #> [1] 4 #> #> $z #> [1] 5 6 7 8 9 10 11 12 13 14 #>