R 矩阵中跨特定行的行和
这是我的矩阵。现在我想分别在各个主题行中找到每个主题的总数,并将它们作为新列添加到上面的矩阵中,作为第5列。然而,我的代码,即class.marks.chemistry你是说这个吗R 矩阵中跨特定行的行和,r,matrix,rowsum,R,Matrix,Rowsum,这是我的矩阵。现在我想分别在各个主题行中找到每个主题的总数,并将它们作为新列添加到上面的矩阵中,作为第5列。然而,我的代码,即class.marks.chemistry你是说这个吗 final.marks # raj sanga rohan rahul #physics 45 43 44 49 #chemistry 47 45 48 47 #total 92 88 92 96 如果df是一个矩阵而不是da
final.marks
# raj sanga rohan rahul
#physics 45 43 44 49
#chemistry 47 45 48 47
#total 92 88 92 96
如果df是一个矩阵而不是data.frame,上述方法也适用
如果你看?行和,你会发现x参数需要
两个或更多维度的数组,包含数字,
复数、整数值或逻辑值,或数字数据帧
因此,在您的情况下,我们必须将整个data.frame或矩阵作为参数传递,而不是像您那样传递特定的列。另一种选择是在矩阵上使用addmargins
哦,非常感谢,只是一个问题,如果我必须提取一个主题的行和作为一个新变量,而不在主矩阵中创建一个新列,该怎么办
# 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
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