R: apply function to matrix with vector elements as argument

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.

+5
source share
2 answers

Mapply definitely an opportunity. This should work:

 mapply(MYFUNC, x = as.data.frame(t(df)), Var = var2) #V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 #5.0795111 2.8693537 1.8285747 1.3640238 0.8300597 0.6280441 0.7706310 0.6720132 0.5719003 0.4259674 

The problem I am facing is that Mapply accepts either vectors or lists. There are no lists in R matrices, but data.frame . All you have to do is transpose your matrix and convert it to data.frame , and then Mapply work. Each column in data.frame is an element in the list, so we need to transpose it (so that each row mapped to each element of the vector).

+5
source

Since there are two arguments that should correspond to the corresponding rows and elements in the matrix / vector, respectively, we can scroll through the sequence of rows, a subset of the data and apply the function

 sapply(seq_len(nrow(df)), function(i) MYFUNC(df[i,], Var = var2[i])) #[1] 5.0795111 2.8693537 1.8285747 1.3640238 0.8300597 0.6280441 #[7] 0.7706310 0.6720132 0.5719003 0.4259674 

For a specific example, it can be vectorized using rowSums

 rowSums(df)/var2 #[1] 5.0795111 2.8693537 1.8285747 1.3640238 0.8300597 0.6280441 #[7] 0.7706310 0.6720132 0.5719003 0.4259674 
+2
source

Source: https://habr.com/ru/post/1267202/


All Articles