按R中的行求和

按R中的行求和,r,sum,R,Sum,让我重新回答我的问题,如何按行对数字求和,并在最后一列后面列出总和,形成一个新的列,如第二个表(sum=a+b+c+d+e) 我还想知道,如果有些值是N/A,我还能把它们当作数字吗 样本输入: a b c d e 1 90 67 18 39 74 2 100 103 20 45

让我重新回答我的问题,如何按行对数字求和,并在最后一列后面列出总和,形成一个新的列,如第二个表(sum=a+b+c+d+e)

我还想知道,如果有些值是N/A,我还能把它们当作数字吗

样本输入:

     a          b           c          d            e
1    90         67          18         39           74
2    100        103         20         45           50 
3    80         87          23         44           89
4    95         57          48         79           90
5    74         81          61         95           131
期望输出:

     a          b           c          d            e    sum
1    90         67          18         39           74   288
2    100        103         20         45           50   318
3    80         87          23         44           89   323
4    95         57          48         79           90   369
5    74         81          61         95           131  442 

要添加行和,可以使用
addmargins

M <- matrix(c(90,67,18,39,74), nrow=1)
addmargins(M, 2)   #2 = row margin
#      [,1] [,2] [,3] [,4] [,5] [,6]
# [1,]   90   67   18   39   74  288
M考虑使用apply()。例如:

set.seed(10) # optional, but this command will replicate data as shown

# create some data
x <-matrix(rnorm(1:25),nrow=5,ncol=5) # 5x5 matrix of random numbers
x
            [,1]       [,2]       [,3]        [,4]       [,5]
[1,]  0.01874617  0.3897943  1.1017795  0.08934727 -0.5963106
[2,] -0.18425254 -1.2080762  0.7557815 -0.95494386 -2.1852868
[3,] -1.37133055 -0.3636760 -0.2382336 -0.19515038 -0.6748659
[4,] -0.59916772 -1.6266727  0.9874447  0.92552126 -2.1190612
[5,]  0.29454513 -0.2564784  0.7413901  0.48297852 -1.2651980

x.sum <-apply(x,1,sum) # sum the rows. Note: apply(x,2,sum) sums cols

x.sum
[1]  1.003356605 -3.776777904 -2.843256446 -2.431935624 -0.002762636

# attach new column (x.sum) to matrix x  
x.sum.1 <-cbind(x,x.sum)

x.sum.1
                                                                    x.sum
[1,]  0.01874617  0.3897943  1.1017795  0.08934727 -0.5963106  1.003356605
[2,] -0.18425254 -1.2080762  0.7557815 -0.95494386 -2.1852868 -3.776777904
[3,] -1.37133055 -0.3636760 -0.2382336 -0.19515038 -0.6748659 -2.843256446
[4,] -0.59916772 -1.6266727  0.9874447  0.92552126 -2.1190612 -2.431935624
[5,]  0.29454513 -0.2564784  0.7413901  0.48297852 -1.2651980 -0.002762636
set.seed(10)#可选,但此命令将复制数据,如图所示
#创建一些数据

x假设您拥有数据帧
df
,那么您可以尝试以下方法:

# Assuming the columns a,b,c,d,e are at indices 1:5
df$sum = rowSums(df[ , c(1:5)], na.rm = T)
或者你也可以试试这个:

transform(df, sum=rowSums(df), na.rm = T)

您可以直接发布代码,而无需发布刚刚发布的图像,但不需要发布代码。@MrFlick使用带addmargins的rowsum的答案是标准答案,如果这不起作用,请发布您尝试过的代码,并解释您使用itOr时遇到的问题,以避免重新定义函数-
cbind(M,rowSums(M,na.rm=TRUE))
谢谢@MrFilck的快速回复。但也许我没有把我的问题说清楚,我只是收回我的问题,你能再帮我一次吗?我的解决方案有什么问题吗?你还没有做出一个好的决定。所涉及对象的类别是什么?矩阵?一张桌子?数据帧<代码>M这是一个矩阵。抱歉误会了,我是R的新手。
transform(df, sum=rowSums(df), na.rm = T)