• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

R的按行求和

用户头像
it1352
帮助1

问题说明

让我重新提出我的问题,我如何按行对数字求和,并列出最后一列后面的总和,形成一个像第二个表一样的新列(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 

正确答案

#1

要添加行总和,可以使用 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

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfekkg
系列文章
更多 icon
同类精品
更多 icon
继续加载