-1

I know this is an elementary question but I simply can't find an answer.

I have a matrix and would like to add each column to get its sum.

Adding should be done for each row.

I've tried rowsums but that only works for arrays.

Is there an easy way to do this for matrices?

An example:

1  2 
1  4
3  4
4  5
5  5

Desired output:

3
4
7
9
10
user1723765
  • 6,179
  • 18
  • 57
  • 85
  • `?colSums` ... ? (I don't know what you mean by "rowsums ... only works for arrays" -- `rowSums` certainly works on matrices, but won't be much use if you want column sums ...) Your terminology isn't very clear -- can you show us a tiny example and the desired results? – Ben Bolker Jan 01 '13 at 19:01
  • Error in colSums(a) : 'x' must be numeric > – user1723765 Jan 01 '13 at 19:02
  • OK, then we need a reproducible example: try http://tinyurl.com/reproducible-000 . It sounds like you have a *data frame* with some non-numeric columns. – Ben Bolker Jan 01 '13 at 19:03
  • 1
    @LarsKotthoff , your solution gives identical results to `rowSums(data)`: it's more general, but slower. It's unclear to me from the wording whether the OP really wants row sums or column sums, but they're having other problems in any case. – Ben Bolker Jan 01 '13 at 19:04
  • here's the data: https://dl.dropbox.com/u/22681355/a.csv there shouldn't be any non-numeric column in there – user1723765 Jan 01 '13 at 19:05
  • The _See Also_ section of `?sum` tells you to read `?colSums`. – Joshua Ulrich Jan 01 '13 at 19:27
  • 2
    voting to close as too localized, as it seems that the real problem is some sort of (undisclosed) issue with reading the data into R ... – Ben Bolker Jan 01 '13 at 19:39
  • This question seems similar, but the issue of non-numeric column(s) remains unexplained in the current example in the above post: http://stackoverflow.com/questions/3991905/vector-that-is-sum-of-rows-in-r – Mark Miller Jan 01 '13 at 20:32

1 Answers1

3
# download and read in your file from dropbox
dropbox.data <- url("http://dl.dropbox.com/u/22681355/a.csv")

# import the data into R
mat <- read.csv( dropbox.data )

# look at the class of each column
sapply( mat , class )
# all columns are numeric for sure
sapply( mat , is.numeric )

# both of these work fine
colSums( mat )

rowSums( mat )
Anthony Damico
  • 5,779
  • 7
  • 46
  • 77