如何将以下格式转换为循环?
alphateam_df <- dplyr::filter(data, grepl("alphateam", Winners))
alphateam_mean <- mean(alphateam_df$growth)
betateam_df <- dplyr::filter(data, grepl("betateam", Winners))
betateam_mean <- mean(betateam_df$growth)
在其他语言中,我会写一些类似的东西:
for (team in c("alphateam","betateam")) {
{team}_df <- dplyr::filter(data, grepl({team}, Winners))
{team}_mean <- mean({team}_df$growth)
}
通过一些搜索我得到了以下内容,但卡在了平均()位上。还想知道它是否需要这么复杂?
for (team in c("alphateam", "betateam")) {
assign(paste(team, "_df", sep = ''), dplyr::filter(full, grepl(team, Winners)))
assign(paste(team, "_mean", sep = ''), mean(...)
}
答案 0 :(得分:0)
正如@ mt1022已经提到的那样,您可能需要考虑不使用for循环。以下示例使用group_by
中的summarise
和dplyr
函数来获取每组获胜者的平均值。
suppressPackageStartupMessages(library(dplyr))
# example data
df <- tibble(Winners = c("alphateam", "betateam", "alphateam", "alphateam",
"betateam", "betateam"),
growth = c(4, 7, 2, 12, 7, 10))
# mean for each Winners group
df %>%
group_by(Winners) %>%
summarise(mean_growth = mean(growth))
#> # A tibble: 2 x 2
#> Winners mean_growth
#> <chr> <dbl>
#> 1 alphateam 6
#> 2 betateam 8
有关详细信息,请参阅summarise
示例http://dplyr.tidyverse.org/reference/summarise.html