Alison Bennett
Alison Bennett

Reputation: 315

Calculating the sum of a matrix row in R

How would I calculate the sum of a row in a simple matrix in R?

My matrix is:

                     circle.sentancing.group control.group
less.serious                              34          3690
more.serious.or.same                      27          4560

I want to calculate the sum of the row less.serious. I have tried using rowSums but this gives me the sum of all rows and I need the sum of this row only for the next calculation.

NB: the columns and rows have been labelled using rownames

Upvotes: 2

Views: 3030

Answers (1)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193537

Why not just use sum? Assuming your matrix is named "M", try:

sum(M["less.serious", ])
# [1] 3724

Basically, you can use [ to extract the relevant rows or columns using the structure [rowstoselect, columnstoselect]. When you don't specify any columns, it selects all of them.

You can use the names of the rows or the index position. For instance, M[1, ] is the same as M["less.serious", ].

Upvotes: 2

Related Questions