This is one way to do it:
results <- mapply(function(i,j) b[[i]](a[[j]]), i=1:length(b), j=1:length(a))
It gives you:
> results
[,1] [,2]
[1,] 1 5
[2,] 2 6
[3,] 3 7
سؤال
I have 2 variables, a
and b
. a
is potentially very large. b
is always a vector of functions that can be applied to each column in the data frame a
.
a <- data.frame(col1=c(1, 2, 3), col2=c(4, 5, 6))
b <- c(as.double, function(x) {1+x})
So the result that I want is that function b[1]
is applied to col1, b[2]
is applied to col2, and so on for all columns. I feel lapply should be used here but documentation seems to say that it can only have one function. I could use a loop I suppose but a "vectorised" way would be nice.
المحلول
This is one way to do it:
results <- mapply(function(i,j) b[[i]](a[[j]]), i=1:length(b), j=1:length(a))
It gives you:
> results
[,1] [,2]
[1,] 1 5
[2,] 2 6
[3,] 3 7