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!!
For small data, it might be interesting to convert the
data.frame
to atable
then useaddmargins()
.With this sample data
and this helper function
you could do
to get
Probably not super useful in this case, but a fun use of
addmargins
nonetheless.I think you want this:
Four previous answers and only one showing a result? What's up with that? Here's one
You wrote that
You won't have to write any loops at all. The row and column functions operate on all the row and all the columns, with no looping.
Please consult the documentation for
?rowSums
and?colSums
.It's not clear from your post exactly what
MergedData
is. Assuming it's adata.frame
, the problem is your indexingMergedData[Test1, Test2, Test3]
. If it is adata.frame
, you'd like to run something like:or
if you only want to use the columns named
"Test1"
,"Test2"
, and"Test3"
(if they indeed are named so).If this doesn't work. Please show us the output of
str(MergedData)
.You need to provide a minimal reproducible example of the error to get any really helpful answers.
You could use:
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).
Here's a way to do it with
dplyr
andreshape2
: