Saturday 25 July 2015

R: apply function

"apply" function returns a vector or array or list of values obtained by applying a function to margins of an array or matrix.

Syntax
apply(X, MARGIN, FUN, ...)

X : Represents an array including matrix
MARGIN : It is a vector representing dimension names, 1 repersent rows, 2 represent columns, c(1,2) represent rows and columns
FUN : Represents the function to be applied

... : Optional arguments passed to the function FUN

> matrix1 <- matrix(1:50, nrow=5, ncol=10)
> matrix1
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]    1    6   11   16   21   26   31   36   41    46
[2,]    2    7   12   17   22   27   32   37   42    47
[3,]    3    8   13   18   23   28   33   38   43    48
[4,]    4    9   14   19   24   29   34   39   44    49
[5,]    5   10   15   20   25   30   35   40   45    50
> 
> 
> apply(matrix1, 1, sum)
[1] 235 245 255 265 275
> 
> apply(matrix1, 2, sum)
 [1]  15  40  65  90 115 140 165 190 215 240
> 
> apply(matrix1, 1, mean)
[1] 23.5 24.5 25.5 26.5 27.5
> 
> apply(matrix1, 2, mean)
 [1]  3  8 13 18 23 28 33 38 43 48

apply(matrix1, 1, sum)
Calculate row sums

apply(matrix1, 2, sum)
Calculate column sums

apply(matrix1, 1, mean)
Calculate row means

apply(matrix1, 2, mean)
Calculate column means



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment