【问题标题】:How to add a total column in last row in R dataframe having value with % [duplicate]如何在 R 数据框中的最后一行添加总列,其值为 % [重复]
【发布时间】:2020-04-22 15:05:37
【问题描述】:

我在 R 中有以下提到的数据框:

country    product          profit_perc
USA        100              15.2%
Canada     10               10.25%
Russia     50               19.72%
Japan      30               25.23%

所需的数据框:

country    product          profit_perc
USA        100              15.2%
Canada     10               10.25%
Russia     50               19.72%
Japan      30               25.23%
Total      190              70.4%

【问题讨论】:

  • 您的数据框如何存储“15.2%”?是存储15.2,然后使用格式函数提供“%”吗?
  • @JohnGarland:不,我从 MySQL 表中获取这些详细信息,该表具有这种格式的值。

标签: r dataframe dplyr tidyverse


【解决方案1】:
library(data.table)
d <- read.table(text = "
country    product          profit_perc
USA        100              15.2
Canada     10               10.25
Russia     50               19.72
Japan      30               25.23", header=T
)

d <- setDT(d)
vars <- c("product", "profit_perc")

d <- rbindlist(list(
  d,
  d[,  lapply(.SD, sum), .SDcols=vars ][,country := "Tot"]
), use.names = T)

   country product profit_perc
1:     USA     100       15.20
2:  Canada      10       10.25
3:  Russia      50       19.72
4:   Japan      30       25.23
5:     Tot     190       70.40

也可以直接传递列的索引:

d <- rbindlist(list(
  d,
  d[,  lapply(.SD, sum), .SDcols=c(2:3) ][,country := "Tot"]
), use.names = T)

【讨论】:

  • 当我传递像Vars&lt;-c(2:6) 这样的列时,它不起作用。
  • 收到错误Error in FUN(X[[i]], ...) : invalid 'type' (character) of argument
  • 为什么是 2:6?,我只看到 2 列
  • 对于示例的观点,我只提到了两列。虽然,我手动输入了列名,但仍然出现同样的错误。
  • 如果您不展示您尝试过的内容,将很难提供帮助。请注意,在我的代码中,我使用了 vars 而不是 Vars。它可以是名称向量,也可以是列索引中的向量。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-13
  • 1970-01-01
  • 2021-07-30
  • 2021-12-20
相关资源
最近更新 更多