Social Media Research

02 R Data Analysis


Question

Explain the build in function apply()


Answer

apply(matrix, row_or_col, fun) applies a function (e.g. sum) to either the rows or columns of a matrix.

Example function sum: If row_or_col is 1 then all cells in a row are added together and a sum is displayed for every row. If it is 2 then all columns are summed.

> m
      [,1] [,2]
 [1,]    1    1
 [2,]    2    2
 [3,]    3    3
 [4,]    4    4
 [5,]    5    5
 [6,]    6    6
 [7,]    7    7
 [8,]    8    8
 [9,]    9    9
[10,]   10   10
> apply(m,1,sum)
 [1]  2  4  6  8 10 12 14 16 18 20
> apply(m,2,sum)
[1] 55 55



Comments