Togaware DATA MINING
Desktop Survival Guide
by Graham Williams
Google


Sum of Columns

The colSums function is an optimised function for calculating the sums of columns in an array. The example here also illustrates how to format output to make large numbers much easier to read, by including commas. The times can be obtained using the system.time function.



> A <- matrix(runif(10000000, 0, 100), ncol=10)
> colSums(A)			   # Optimised: 0.1 seconds
> rep(1, nrow(A)) %*% A		   # Slower: 0.3 seconds
> apply(A, 2, sum)		   # Slowest: 0.7 seconds
> format(colSums(A), big.mark=",")

 [1] "49,966,626" "49,968,075" "49,977,689" "50,010,843" "50,038,271"
 [6] "49,936,119" "50,027,467" "49,985,741" "50,065,027" "49,985,044"

> colSums(A)

 [1] 49966626 49968075 49977689 50010843 50038271 49936119 50027467 49985741
 [9] 50065027 49985044



Copyright © 2004-2006 [email protected]
Support further development through the purchase of the PDF version of the book.
Brought to you by Togaware.