Apply a function to every row of a matrix or a data frame Apply a function to every row of a matrix or a data frame r r

Apply a function to every row of a matrix or a data frame


You simply use the apply() function:

R> M <- matrix(1:6, nrow=3, byrow=TRUE)R> M     [,1] [,2][1,]    1    2[2,]    3    4[3,]    5    6R> apply(M, 1, function(x) 2*x[1]+x[2])[1]  4 10 16R> 

This takes a matrix and applies a (silly) function to each row. You pass extra arguments to the function as fourth, fifth, ... arguments to apply().


In case you want to apply common functions such as sum or mean, you should use rowSums or rowMeans since they're faster than apply(data, 1, sum) approach. Otherwise, stick with apply(data, 1, fun). You can pass additional arguments after FUN argument (as Dirk already suggested):

set.seed(1)m <- matrix(round(runif(20, 1, 5)), ncol=4)diag(m) <- NAm     [,1] [,2] [,3] [,4][1,]   NA    5    2    3[2,]    2   NA    2    4[3,]    3    4   NA    5[4,]    5    4    3   NA[5,]    2    1    4    4

Then you can do something like this:

apply(m, 1, quantile, probs=c(.25,.5, .75), na.rm=TRUE)    [,1] [,2] [,3] [,4] [,5]25%  2.5    2  3.5  3.5 1.7550%  3.0    2  4.0  4.0 3.0075%  4.0    3  4.5  4.5 4.00


Here is a short example of applying a function to each row of a matrix.(Here, the function applied normalizes every row to 1.)

Note: The result from the apply() had to be transposed using t() to get the same layout as the input matrix A.

A <- matrix(c(  0, 1, 1, 2,  0, 0, 1, 3,  0, 0, 1, 3), nrow = 3, byrow = TRUE)t(apply(A, 1, function(x) x / sum(x) ))

Result:

     [,1] [,2] [,3] [,4][1,]    0 0.25 0.25 0.50[2,]    0 0.00 0.25 0.75[3,]    0 0.00 0.25 0.75