Aaron
Aaron

Reputation: 181

Trouble with a function inside of a for loop

I've created a set of objects:

rs_s = {
rs_s_72 <- regular_season %>% filter(season == 72)
rs_s_73 <- regular_season %>% filter(season == 73)
rs_s_74 <- regular_season %>% filter(season == 74)
rs_s_75 <- regular_season %>% filter(season == 75)
rs_s_76 <- regular_season %>% filter(season == 76)
rs_s_77 <- regular_season %>% filter(season == 77)
rs_s_78 <- regular_season %>% filter(season == 78)
rs_s_79 <- regular_season %>% filter(season == 79)
rs_s_80 <- regular_season %>% filter(season == 80)
rs_s_81 <- regular_season %>% filter(season == 81)
rs_s_82 <- regular_season %>% filter(season == 82)
rs_s_83 <- regular_season %>% filter(season == 83)
rs_s_84 <- regular_season %>% filter(season == 84)
rs_s_85 <- regular_season %>% filter(season == 85)
}

I then tried to take the mean of the "correct" column within each object with this code, but it doesn't seem to be working:

for (i in rs_s){
 mean('correct')
  print(mean)
}

If someone knows, could someone tell me where I might have gone wrong, and how I could fix it?

EDIT: I have also looked at several other questions on this site and other sites but none have seemed especially pertinent to this question.

Upvotes: 1

Views: 38

Answers (1)

akrun
akrun

Reputation: 887118

If we have created objects that starts with 'rs_s_' in the global env, get those objects based on the pattern with mget into a list, extract the correct column and get the mean by looping over the list with sapply

sapply(mget(ls(pattern = '^rs_s_\\d+$')), function(x) mean(x$correct))

Based on the syntax, it may be better to do a group_by with 'season' instead of filtering, thus avoiding the step of creating multiple objects, then gathering those objects to calculate the mean

library(dplyr)
regular_season %>%
    group_by(season) %>%
    summarise(Mean = mean(correct, na.rm = TRUE), .groups = 'drop')

If we need only the mean for particular 'season', then do the filter before the group_by

regular_season %>%
   filter(season %in% 72:85) %>%
   group_by(season) %>%
   summarise(Mean = mean(correct, na.rm = TRUE), .groups = 'drop') 

Upvotes: 3

Related Questions