I have a nested list like this:
foo <- list(
a = list("a1" = c(1,2,3), "a2" = c(4,5,6), "a3" = c(7,8,9)),
b = list("b1" = c(10, 20, 30), "b2" = c(40, 50, 60), "b3" = c(70, 80, 90)),
...
...
...
)
I want to compute the sum of corresponding nested list elements: i.e a1+b1+..., a2+b2+..., a3+b3+... If there are just two nested list elements, a and b, they can be done like this
mapply(function(x,y) x+y, foo[[1]], foo[[2]], SIMPLIFY = FALSE)
But if there is a variable number of nested list elements like a, b, c, d, .. etc. I would like to write a generic script that can do this
You could do:
l = min(lengths(foo))
lapply(seq(l), \(x) Reduce(`+`, unlist(lapply(foo, `[`, x), recursive = FALSE)))
# [[1]]
# [1] 11 22 33
#
# [[2]]
# [1] 44 55 66
#
# [[3]]
# [1] 77 88 99
Or, if you want the sum in each:
sapply(1:3, \(x) Reduce(`+`, unlist(lapply(foo, `[`, x))))
#[1] 66 165 264
We can use Reduce
+ Map
+ list2DF
like below
> unname(as.list(Reduce(`+`, Map(list2DF, foo))))
[[1]]
[1] 11 22 33
[[2]]
[1] 44 55 66
[[3]]
[1] 77 88 99
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With