Row and column sums in R

user3620588 picture user3620588 · May 9, 2014 · Viewed 49.8k times · Source

This is an example of how my data set (MergedData) looks like in R, where each of my participants (5 rows) obtained a score number in every test (7 columns). I would like to know the total score of all tests combined (all columns) but for each participant (row).

Also, my complete data set has more than just these few variables, so if possible, I would like do it using a formula & loop and not having to type row by row/column by column.

Participant TestScores     
ParticipantA    2   4   2   3   2   3   4
ParticipantB    1   3   2   2   3   3   3
ParticipantC    1   4   4   2   3   4   2
ParticipantD    2   4   2   3   2   4   4
ParticipantE    1   3   2   2   2   2   2

I have tried this but it doesn't work:

Test_Scores <- rowSums(MergedData[Test1, Test2, Test3], na.rm=TRUE)

I get the following error-message:

Error in `[.data.frame`(MergedData, Test1, Test2, Test3,  : 
  unused arguments

How do I solve this? Thank you!!

Answer

Matthew Lundberg picture Matthew Lundberg · May 9, 2014

I think you want this:

rowSums(MergedData[,c('Test1', 'Test2', 'Test3')], na.rm=TRUE)