0
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 或任何形式的脚本或编程背景非常陌生。

4

2 回答 2

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

df如果是 amatrix而不是 a ,上述方法也适用data.frame


如果你看?rowSums你会发现这个x论点需要是

二维或多维数组,包含数字、复数、整数或逻辑值,或数字数据框。

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

于 2018-06-11T07:52:26.987 回答
0

另一种选择是addmarginsmatrix

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
于 2018-06-11T16:08:12.320 回答