Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Row and column sums in R

Tags:

r

rowsum

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!!

like image 869
user3620588 Avatar asked Dec 04 '22 06:12

user3620588


2 Answers

I think you want this:

rowSums(MergedData[,c('Test1', 'Test2', 'Test3')], na.rm=TRUE)
like image 144
Matthew Lundberg Avatar answered Dec 15 '22 15:12

Matthew Lundberg


You could use:

MergedData$Test_Scores_Sum <- rowSums(MergedData[,2:8], na.rm=TRUE)

Where 2:8 are all the columns (tests) you want to sum up. This way it will create another column in your data.

This way you dont have to type each column name and you can still have other columns in you data frame which will not be summed up. Note however, that all columns of tests you want to sum up should be beside each other (as in your example data).

like image 33
talat Avatar answered Dec 15 '22 15:12

talat