【问题标题】:How to mutate by groups?如何按组变异?
【发布时间】:2020-06-29 14:35:00
【问题描述】:

我正在尝试根据每个组的平均函数来改变一个新变量。我尝试使用 R 中可用的预加载数据框“ToothGrowth”运行此代码。

输出结果不正确,似乎是将每个组的平均值作为列表循环,而不是分配给每个组。

显示我想要实现的目标的图表:

data("ToothGrowth")
head(ToothGrowth)

tg.tb01<-ToothGrowth %>% 
group_by(supp, dose) %>% # mydata has 3 more variables. 
  summarise(mean = mean(len)) %>% 
  print()
ToothGrowth %>% 
  group_by(supp) %>%
  mutate(submean2 = len - tg.tb01$mean/tg.tb01$dose)

【问题讨论】:

  • 如果您可以用示例中的数字举例说明您希望输出数据的外观,那就太好了。

标签: r dataframe group-by dplyr


【解决方案1】:

您不需要其他数据集来存储平均值。往下看:

library(dplyr)
library(datasets)

ToothGrowth %>% 
  group_by(supp, dose) %>%
  mutate(lenmean = mean(len),
         submean2 = len - lenmean/dose)

#> # A tibble: 60 x 5
#> # Groups:   supp, dose [6]
#>      len supp   dose lenmean submean2
#>    <dbl> <fct> <dbl>   <dbl>    <dbl>
#>  1   4.2 VC      0.5    7.98   -11.8 
#>  2  11.5 VC      0.5    7.98    -4.46
#>  3   7.3 VC      0.5    7.98    -8.66
#>  4   5.8 VC      0.5    7.98   -10.2 
#>  5   6.4 VC      0.5    7.98    -9.56
#>  6  10   VC      0.5    7.98    -5.96
#>  7  11.2 VC      0.5    7.98    -4.76
#>  8  11.2 VC      0.5    7.98    -4.76
#>  9   5.2 VC      0.5    7.98   -10.8 
#> 10   7   VC      0.5    7.98    -8.96
#> # ... with 50 more rows

【讨论】:

    【解决方案2】:

    如果我理解正确,您应该改用。请用数字指定您想要的输出。

    tg.tb01<-ToothGrowth %>% 
        group_by(supp, dose) %>%
        mutate(mean = mean(len)) %>%
        ungroup() %>%
        group_by(supp) %>%
        mutate(submean2 = len - mean/dose)
    

    【讨论】:

      猜你喜欢
      • 2018-12-13
      • 2017-05-14
      • 2021-06-24
      • 2013-10-30
      • 2014-01-11
      • 2021-02-11
      相关资源
      最近更新 更多