我是 R 的新手,正在寻找当其他列具有相应的行条目时对列求和的方法。
我使用了以下功能
group_by(type_of_pastry, allergen) %>% dplyr::summarize(n = n())
下一个任务是根据糕点的类型,用“体积”列中的值总和填充最新列“总计”。例如,第 1 行和第 2 行(羊角面包)应分别显示 43 和第 3 行和第 4 行(奶酪奶油蛋卷)的 35。
在花时间寻找解决方案后,他们中的大多数人将我引向了
aggregate
,这将改变数据集的结构,而目标是保持上述结构。任何指导将不胜感激。谢谢!
试试这个,但是会删除其他列:
df %>%
group_by(type_of_pastry) %>%
summarise(Total = sum(count))
# A tibble: 2 × 2
type_of_pastry Total
<chr> <dbl>
1 Cheese brioche 35
2 Croissant 43
或者这个,它保留了其他列(但复制了
Total
):
df %>%
group_by(type_of_pastry) %>%
mutate(Total = sum(count))
# A tibble: 4 × 4
# Groups: type_of_pastry [2]
type_of_pastry allergen count Total
<chr> <chr> <dbl> <dbl>
1 Croissant Nut 23 43
2 Croissant None 20 43
3 Cheese brioche Nut 18 35
4 Cheese brioche Milk 17 35
或者这个,它以紧凑的形式为您提供一切:
df %>%
group_by(type_of_pastry) %>%
summarise(
allergen = str_c(allergen, collapse = ", "),
Total = sum(count))
# A tibble: 2 × 3
type_of_pastry allergen Total
<chr> <chr> <dbl>
1 Cheese brioche Nut, Milk 35
2 Croissant Nut, None 43