在矩阵中的特定行中的rowums

时间:2018-06-11 07:48:04

标签: r matrix rowsum

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

这是我的矩阵。现在我想在各个主题行中分别找到每个主题的总数,并将它们作为新列添加到上面的矩阵作为第5列。然而,我的代码,class.marks.chemistry<- rowSums(final.marks[2,])不断产生错误说

  

说错误   rowSums(final.marks [2,]):     'x'必须是至少包含两个维度的数组

你能帮我解决一下吗?我是R或任何形式的脚本或编程背景的新手。

2 个答案:

答案 0 :(得分:1)

你是说这个吗?

# 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

如果dfmatrix而不是data.frame,则上述方法也有效。

如果查看?rowSums,您可以看到x参数需要

  

包含数字的两个或多个维度的数组,             复数,整数或逻辑值,或数字数据框。

因此,在您的情况下,我们必须将整个data.frame(或matrix)作为参数传递,而不是通过特定列(就像您所做的那样)。

答案 1 :(得分:0)

另一种选择是在addmargins

上使用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