【问题标题】:Acceptable practice to use 'group_by' stats in mutate?在变异中使用“group_by”统计数据的可接受做法?
【发布时间】:2021-09-29 06:37:14
【问题描述】:

过去,当我需要在部分基于“group_by”汇总统计的 R 数据框中创建一个新变量时,我总是使用以下顺序:

(1) 使用 group_by() 和 summarise() 从基础(未分组)数据框中的数据计算“组统计”

(2)将基础数据框与上一步的结果连接起来,然后使用mutate计算新的变量值。

但是,(在使用 dplyr 多年之后!)我不小心在 mutate 步骤中进行了“总结”,一切似乎都奏效了。这在下面代码 sn-p 中的选项 #2 中进行了说明。我假设选项 #2 没问题,因为我使用这两个选项得到了相同的结果,并且因为我今天在网上找到了类似的示例。但是,我不确定。

选项 #2 是可接受的做法,还是首选选项 #1(如果是,为什么)?

set.seed(123)
df <- tibble(year_ = c(rep(c(2019), 4), rep(c(2020), 4)),
             qtr_ = c(rep(c(1,2,3,4), 2)),
             foo = sample(seq(1:8)))

# Option 1: calc statistics then rejoin with input data
df_stats <- df %>%
  group_by(year_) %>%
  summarize(mean_foo = mean(foo))

df_with_stats <- left_join(df, df_stats) %>%
  mutate(dfoo = foo - mean_foo)

# Option 2: everything in one go
df_with_stats2 <- df %>%
  group_by(year_) %>%
  mutate(mean_foo = mean(foo),
         dfoo = foo - mean_foo)

df_with_stats
# A tibble: 8 x 5
  year_  qtr_   foo mean_foo  dfoo
  <dbl> <dbl> <int>    <dbl> <dbl>
1  2019     1     7        6     1
2  2019     2     8        6     2
3  2019     3     3        6    -3
4  2019     4     6        6     0
5  2020     1     2        3    -1
6  2020     2     4        3     1
7  2020     3     5        3     2
8  2020     4     1        3    -2
df_with_stats2
# A tibble: 8 x 5
# Groups:   year_ [2]
  year_  qtr_   foo mean_foo  dfoo
  <dbl> <dbl> <int>    <dbl> <dbl>
1  2019     1     7        6     1
2  2019     2     8        6     2
3  2019     3     3        6    -3
4  2019     4     6        6     0
5  2020     1     2        3    -1
6  2020     2     4        3     1
7  2020     3     5        3     2
8  2020     4     1        3    -2

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    选项 2 很好,如果您不需要中间对象,甚至不需要在 mutate 语句中创建 mean_foo

    df %>% group_by(year_) %>% mutate(dfoo=foo-mean(foo))
    

    还有,data.table

    setDT(df)[,dfoo:=foo-mean(foo), by =year_]
    

    【讨论】:

    • #Langtang:在代数上你当然是正确的,但是这种分离对于演示 mutate 如何包含多个新对象很有用(尤其是对于 dplyr 新手)。
    • 同意@WBarker.. 你是对的,在许多情况下,可读性比简洁更重要。我不是故意混淆视听。
    猜你喜欢
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 2021-11-20
    • 1970-01-01
    • 2023-01-19
    相关资源
    最近更新 更多