【问题标题】:How to select columns that were not summarise after group_by?如何选择 group_by 之后未汇总的列?
【发布时间】:2019-01-18 17:42:51
【问题描述】:
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 值将相同。

【问题讨论】:

  • df %&gt;% group_by(c) %&gt;% summarise(new_a=sum(a), new_b=sum(b)) %&gt;% select(new_a, new_b, c)

标签: r dplyr


【解决方案1】:

如果您不使用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 (v0.2.1) 于 2019-01-18 创建

【讨论】:

    猜你喜欢
    • 2016-09-25
    • 1970-01-01
    • 2021-12-15
    • 2021-11-14
    • 2014-08-31
    • 1970-01-01
    • 2021-08-12
    • 1970-01-01
    • 2022-01-12
    相关资源
    最近更新 更多