R中的按行求和 [英] Sum by Rows in R
本文介绍了R中的按行求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
让我重新提出我的问题,我如何按行对数字求和,并列出最后一列后面的总和,形成一个像第二个表一样的新列(sum = a + b+ c + d + e)?
Let me reclaim my question, how I can sum the numbers by row, and list the sum follow by the last column, forming a new column like the second table (sum = a + b+ c + d + e)?
而且我还想知道如果某些值是 N/A 怎么办,我还能将它们视为数字吗?
And I also want to know what if some of the values are N/A, can I still treat them as numbers?
样本输入:
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
To add a row sum, you can use 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
如果您缺少数据,则需要将边距函数更改为可以正确处理 NA 值的内容
If you have missing data, you'll need to change the margin function to something that will properly handle the NA values
M<-matrix(c(90,67,18,NA,74), nrow=1)
addmargins(M, 2, FUN=function(...) sum(..., na.rm=T))
# [,1] [,2] [,3] [,4] [,5] [,6]
# [1,] 90 67 18 NA 74 249
这篇关于R中的按行求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文