I want to apply a function element-wise to a list of dataframes. I am able to apply a simple function but not the more complex one cause I am not sure how to refer to the arguments.
I am able to do the following action on a data frame:
df1 <- data.frame(
A = c(1, 2),
B = c(1, 3)
)
centered <- apply(df1, 2, function(x) x - mean(x))
scaled <- apply(centered, 2, function(x) x/sqrt(sd(x)))
Then I create a list of two data frames (they will have the same number of rows but different number of columns):
df1 <- data.frame(
A = c(1, 2),
B = c(1, 3))
df2 <- data.frame(
A = c(1, 2, 3, 4),
B = c(1, 2, 3, 4))
l=list(df1,df2)
I have learned that mapply seems to do what I want. But, how to apply the actions from above? Here is the mapply for function(x,y). I would like to apply actions centered
and scaled
from above instead:
l_output <- mapply(function(x,y) x*y, x = 2, y = list, SIMPLIFY = FALSE)