r - 整理数据 r 的变量子集求和

标签 r

我想对包含在单个变量中的类别子集求和,在 r 中组织为整齐的数据。

看起来应该很简单,但我只能想到大量的代码行来做。

这是一个例子:

df = data.frame(food = c("carbs", "protein", "apple", "pear"), value = c(10, 12, 4, 3))
df
     food value
1   carbs    10
2 protein    12
3   apple     4
4    pear     3

我希望数据框看起来像这样(将苹果和梨组合成水果):

     food value
1   carbs    10
2 protein    12
3   fruit     7

我能想到的方法是:

library(dplyr)
library(tidyr)

df %>%
spread(key = "food", value = "value") %>%
mutate(fruit = apple + pear) %>%
select(-c(apple, pear)) %>%
gather(key = "food", value = "value")

     food value
1   carbs    10
2 protein    12
3   fruit     7

对于如此简单的事情来说,这似乎太长了。我还可以对数据进行子集化,对行求和,然后进行 rbind,但这似乎也很费力。

有没有更快的选择?

最佳答案

一个因素可以用 forcats::fct_recode 重新编码,但这不一定更短。

library(dplyr)
library(forcats)

df %>%
  mutate(food = fct_recode(food, fruit = 'apple', fruit = 'pear')) %>%
  group_by(food) %>%
  summarise(value = sum(value))
## A tibble: 3 x 2
#  food    value
#  <fct>   <dbl>
#1 fruit       7
#2 carbs      10
#3 protein    12

编辑。

我会在 this comment 中发布代码在这里,因为评论比答案更容易被删除。结果同上。

df %>%
  group_by(food = fct_recode(food, fruit = 'apple', fruit = 'pear')) %>%
  summarise(value = sum(value))

关于r - 整理数据 r 的变量子集求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57680163/

相关文章:

r - 从R中的url读取csv文件时超时

r - 对数据框中的所有变量执行相同的变异

r - 具有缺失值的向量之间的距离

r - 自动增加R软件包的版本

r - ggplot 2 : dot plot with mean and 95% CI for two grouping variables

r - 我将 stat_regline_equation 与 ggscatter 一起使用。有没有办法指定系数的有效数字?

r - 有没有办法选择性地应用这个 stringr 函数?

根据条件将数据帧的某些值替换为另一个数据帧中的值

r - 具有绝对字长的词云

r - MLR 中的警告 "NA used as a default value for learner parameter missing"是什么意思?