将行添加到数据框中,每列的总和 [英] Add row to a data frame with total sum for each column

查看:24
本文介绍了将行添加到数据框中,每列的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,我想在其中添加一个额外的行来汇总每列的值.例如,假设我有以下数据:

I have a data frame where I would like to add an additional row that totals up the values for each column. For example, Let's say I have this data:

x <- data.frame(Language=c("C++", "Java", "Python"), 
                Files=c(4009, 210, 35), 
                LOC=c(15328,876, 200), 
                stringsAsFactors=FALSE)    

数据如下所示:

  Language Files   LOC
1      C++  4009 15328
2     Java   210   876
3   Python    35   200

我的直觉是这样做:

y <- rbind(x, c("Total", colSums(x[,2:3])))

这有效,它计算总数:

> y
  Language Files   LOC
1      C++  4009 15328
2     Java   210   876
3   Python    35   200
4    Total  4254 16404

问题是 Files 和 LOC 列都已经转成字符串了:

The problem is that the Files and LOC columns have all been converted to strings:

> y$LOC
[1] "15328" "876"   "200"   "16404"

我知道发生这种情况是因为我创建了一个向量 c("Total", colSums(x[,2:3]) ,输入既是数字又是字符串,它正在转换所有将元素转换为通用类型,以便所有向量元素都相同.然后同样的事情发生在 Files 和 LOC 列上.

I understand that this is happening because I created a vector c("Total", colSums(x[,2:3]) with inputs that are both numbers and strings, and it's converting all the elements to a common type so that all of the vector elements are the same. Then the same thing happens to the Files and LOC columns.

有什么更好的方法可以做到这一点?

What's a better way to do this?

推荐答案

参见看门人包中的adorn_totals():

library(janitor)
x %>%
  adorn_totals("row")

#>  Language Files   LOC
#>       C++  4009 15328
#>      Java   210   876
#>    Python    35   200
#>     Total  4254 16404

数值列仍然属于 numeric 类.

The numeric columns remain of class numeric.

免责声明:我创建了这个包,包括专为此任务而制作的 adorn_totals().

这篇关于将行添加到数据框中,每列的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆