0
final.marks
#          raj sanga rohan rahul
#physics    45    43    44    49
#chemistry  47    45    48    47
#total      92    88    92    96

This is the matrix I have. Now I want to find the total for each subject separately across respective subject rows and add them as a new column to the above matrix as the 5th column . However my code i.e class.marks.chemistry<- rowSums(final.marks[2,]) keeps producing an error saying

Error saying rowSums(final.marks[2, ]) : 'x' must be an array of at least two dimensions

Can you please help me solve it. I am very new to R or any form of scripting or programming background.

Maurits Evers
  • 49,617
  • 4
  • 47
  • 68

2 Answers2

1

Do you mean this?

# Sample data
df <- read.table(text =
    "          raj sanga rohan rahul
physics    45    43    44    49
chemistry  47    45    48    47
total      92    88    92    96", header  = T)

# Add column total with row sum
df$total <- rowSums(df);
df;
#          raj sanga rohan rahul total
#physics    45    43    44    49   181
#chemistry  47    45    48    47   187
#total      92    88    92    96   368

The above also works if df is a matrix instead of a data.frame.


If you look at ?rowSums you can see that the x argument needs to be

an array of two or more dimensions, containing numeric, complex, integer or logical values, or a numeric data frame.

So in your case we must pass the entire data.frame (or matrix) as an argument, rather than a specific column (like you did).

Maurits Evers
  • 49,617
  • 4
  • 47
  • 68
0

Another option would be to use addmargins on a matrix

addmargins(as.matrix(df), 2)
#         raj sanga rohan rahul Sum
#physics    45    43    44    49 181
#chemistry  47    45    48    47 187
#total      92    88    92    96 368
akrun
  • 874,273
  • 37
  • 540
  • 662