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

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

问题描述

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

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

问题是文件和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.

什么是a更好的方法吗?

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

数字列仍为数值类。

免责声明:我创建了此程序包,其中包括 adorn_totals(),这是为便于说明而设计的结束这项任务。

Disclaimer: I created this package, including adorn_totals() which is made for precisely this task.

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

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