I have a nested list with two or more elements at the top level and want to modify named elements of the sub-lists, e.g. by appending values from a named vector.
Let's assume L
is a list of two elements and N
is a vector with the same number of elements:
L <- list(
foo = list(
x1=1,
x2=c(a=1, b=2)
),
bar = list(
x1=2,
x2=c(e=2, f=3)
)
)
N <- c(n=11, n=12)
Then I want to get a result like this:
list(
foo = list(
x1=1,
x2=c(a=1, b=2, n=11)
),
bar = list(
x1=2,
x2=c(e=2, f=3, n=12)
)
)
It is easy to read the elements of the sub-lists:
lapply(L, "[[", "x2")
So I wonder if there is a similarly compact way to change elements.
CodePudding user response:
We may use Map
to loop over the L
, and corresponding elements of N
, extract the 'x2' component and append the N
values and assign back, return the object (x
)
L2 <- Map(\(x, y)
{
x$x2 <- c(x$x2, n=y)
x
}, L, N)
-checking with OP's output
> all.equal(L2, out)
[1] TRUE
Or a variant is to assign with the name
Map(\(x, y) {x$x2['n'] <- y; x}, L, N)