我想对包含在单个变量中的类别子集求和,在 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/