Suppose I want to apply a function to each row of a matrix. One of the function arguments takes a vector. I would like to apply the first element of the vector to the first line, the second element to the second line, etc.
For instance:
set.seed(123) df<-matrix(runif(100), ncol=10) var2 <- c(1:10) MYFUNC <- function(x, Var=NA){ sum(x)/Var }
I tried this:
apply(df, 1, function(x) MYFUNC(x, Var=var2))
But that gives me a 10x10 matrix with a function applied to each row and Var combination, while I'm only interested in diagonal elements. I also looked at the mapply function, but I'm not sure how to apply it in this case.
Any help would be really appreciated.
source share