Using base R, I would like to apply a different function to each element of a nested list. I know how to apply the same function to a nested list with
lapply(list, lapply, function).
However, I'm looking for an elegant way to apply a different function to each element. The code below works, but I find the use of
function(x) lapply(x, function(x))
is ugly so I'm hoping there's a more elegant solution.
Data <- list(
Panel1 = list(
DF1 = data.frame(A = rnorm(10), B = rnorm(10)),
DF2 = data.frame(A = rnorm(10), B = rnorm(10))
),
Panel2 = list(
DF1 = data.frame(C = rnorm(10), D = rnorm(10)),
DF2 = data.frame(C = rnorm(10), D = rnorm(10))
)
)
Fns <- list(
function(x) lapply(x, function(x) x[1:5, c("B", "A")]),
function(x) lapply(x, function(x) x[1:5, c("D", "C")])
)
Map(function(a, b) b(a), Data, Fns)
?compose
function in thepurrr
package may be helpful for your case. – ChuanMap
ugly? – Rui Barradaslapply(1:2,function(f){ funx <- Fns[[f]] funx(Data[[f]]) })
– Mike