0

How do I convert the following format to a loop?

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)

In other languages I would write something like:

for (team in c("alphateam","betateam")) {
   {team}_df <- dplyr::filter(data, grepl({team}, Winners))
   {team}_mean <- mean({team}_df$growth)
}

With a bit of searching I got as far as the following, but got stuck on the mean() bit. Also wondering if it needs to be this complicated?

for (team in c("alphateam", "betateam")) {
  assign(paste(team, "_df", sep = ''), dplyr::filter(full, grepl(team, Winners)))
  assign(paste(team, "_mean", sep = ''), mean(...)
}
jimbo
  • 176
  • 6
  • 2
    A for-loop might not be the best choice for this kind of jobs. You might be interested in this post: https://stackoverflow.com/questions/11562656/average-data-by-group – mt1022 Sep 16 '17 at 11:52
  • Can you provide a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)? – Samuel Sep 16 '17 at 13:37

1 Answers1

0

As mentioned already by @mt1022, you might want to consider not using a for loop for this. The following example uses the group_by and summarise functions from dplyr to obtain the mean for each group of Winners.

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

For more info see the summarise examples http://dplyr.tidyverse.org/reference/summarise.html

markdly
  • 4,394
  • 2
  • 19
  • 27