0

我正在努力使以下代码正常工作。我拥有的数据是物理测试的data.frame。进行测试的运动员根据“运动特定”参数进行分类。

wingate_benchmarks <- wingate_data %>%
        select(`Sport Specific`,`Minimum power output`,`Average power output`,
           `Relative Average Power`,`Peak Power`,`Time to peak`,`Max. RPM`,`Time to Max. RPM`,`Total Work`) %>%
        group_by(`Sport Specific`) %>%
        dplyr::summarize_at(vars(`Minimum power output`,`Average power output`,
                      `Relative Average Power`,`Peak Power`,`Time to peak`,`Max. RPM`,`Time to Max. RPM`,`Total Work`),
                 list(mean = mean, sd = sqrt((n()-1)/n())*sd))

如果我只使用 sd,它会计算标准偏差,就好像数据是一个样本一样,但它应该被视为完整的人口。因此sqrt((n()-1)/n())加法。

但是 R 不断返回:错误:n()只能在 dplyr 动词中使用。

有没有办法解决这个问题?谢谢!

4

1 回答 1

1

这是一个尝试,不确定它是否适用于您的数据。

wingate_data %>%
  select(`Sport Specific`, `Minimum power output`, `Average power output`,
         `Relative Average Power`, `Peak Power`, `Time to peak`,
         `Max. RPM`, `Time to Max. RPM`, `Total Work`) %>%
  group_by(`Sport Specific`) %>%
  dplyr::summarize(
    across(`Minimum power output`, `Average power output`, `Relative Average Power`,
           `Peak Power`, `Time to peak`, `Max. RPM`, `Time to Max. RPM`, `Total Work`,
           list(mean = ~ mean(.), sd = ~ sqrt((n()-1)/n()) * sd(.))
           ))

我们可以使用mtcars

mtcars %>%
  group_by(cyl) %>%
  summarize(
    across(vs:carb,
           list(mean = ~ mean(.), sd = ~ sqrt((n()-1)/n()) * sd(.))
           ))
# # A tibble: 3 x 9
#     cyl vs_mean vs_sd am_mean am_sd gear_mean gear_sd carb_mean carb_sd
#   <dbl>   <dbl> <dbl>   <dbl> <dbl>     <dbl>   <dbl>     <dbl>   <dbl>
# 1     4   0.909 0.287   0.727 0.445      4.09   0.514      1.55   0.498
# 2     6   0.571 0.495   0.429 0.495      3.86   0.639      3.43   1.68 
# 3     8   0     0       0.143 0.350      3.29   0.700      3.5    1.5  

正如@Limey 在他们的评论中所说,这些summarize_*函数已被 取代across,它通常需要两个参数:变量(tidyselect时尚)和某种形式的函数。

可以通过多种方式提供这些功能:

  • 文字函数, summarize(across(vs:carb, mean));
  • 匿名函数, summarize(across(vs:carb, function(z) mean(z)/2));
  • rlang-style tilde funcs, summarize(across(vs:carb, ~ mean(.))),其中.替换为列(向量);或者
  • 具有上述任何一项的命名列表,例如我们在mtcars上面的工作答案中演示的。
于 2021-08-13T12:02:28.760 回答