I have a 100x20 matrix now I want to add a new column and I have to do the sum of the twenty columns. I am trying to find a function to do this, can any one help
Asked
Active
Viewed 77 times
-2
-
possible duplicate of [Vector that is sum of rows](http://stackoverflow.com/questions/3991905/vector-that-is-sum-of-rows) – Brian Diggs Mar 10 '14 at 18:58
2 Answers
2
You are looking for rowSums
.
if your data is m
m <- matrix(rexp(2000, rate=.1), ncol=20)
#creating totals
mtotal <- rowSums(m)
#adding totals to the matrix
m <- cbind(m,mtotal)

Rfan
- 722
- 6
- 11
0
You want to add a new column to the matrix, with values that are the sum of the existing columns?
Given your matrix in m
, this should do it:
newcol <- sapply(1:nrow(m), function(row) { sum(m[row,]) })
m <- cbind(m, newcol)
UPDATE
I didn't know rowSums
! As @Rfan pointed out, this could be simplified to:
m <- cbind(m, rowSums(m))