colSums, rowSums, colMeans, rowMeans

colSums(x), rowSums(x), colMeans(x), rowMeans(x)
The function apply was described yesterday. The four functions for today’s post provide even faster ways to perform sums and means across rows and columns.
  • x – A matrix.

Example. A matrix with 10,000 rows and 100 columns is created, then I compare the speed of apply against colSums using the system.time function. Lastly, I verify the results are identical.
> x <- matrix(rchisq(10^6, 4), nrow=10^4)
> system.time(y1 <- apply(x, 2, sum))
   user  system elapsed 
  0.040   0.005   0.044 
> system.time(y2 <- colSums(x))
   user  system elapsed 
  0.001   0.000   0.002 
> identical(y1, y2)
[1] TRUE
Tip. Two additional arguments are available within the functions: na.rm to omit missing (i.e. NA) observations in the matrix, and a dims argument that makes it possible to use today’s functions with arrays (see array).

Leave a Reply