df <- data.frame(a=1:100, b=1:100, c='categorical')
df %>% summarise(new_a=sum(a), new_b=sum(b)) %>% select(new_a, new_b, c)
Error: `c` must evaluate to column positions or names, not a function
我怎样才能让上面的代码做我想做的,也就是让c.每个组的 c 值都相同。
最佳答案
如果您未使用 group_by
指定它,则默认行为是汇总并仅包含您在 summarize
中指定的内容,因此在您的代码中,列 c 不会'存在。如果您将其指定为一个组,则该列将被包括在内。
library(dplyr)
df <- data.frame(a=1:100, b=1:100, c='categorical')
df %>%
group_by(c) %>%
summarise(new_a=sum(a), new_b=sum(b)) %>% select(new_a, new_b, c)
#> # A tibble: 1 x 3
#> new_a new_b c
#> <int> <int> <fct>
#> 1 5050 5050 categorical
由 reprex package 创建于 2019-01-18 (v0.2.1)
关于r - 如何选择group_by后未汇总的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54259006/