1

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.

2
  • Hey @akrun Thanks for your comment - do you know how I might phrase it better syntactically? Commented May 6, 2021 at 20:01
  • 1
    Based on the syntax showed, you are creating multiple objects in the global env. i.e. rs_s_72, rs_s_73 etc. The rs_s = {. is not making sense Commented May 6, 2021 at 20:02

1 Answer 1

3

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') 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.