new to R, am using it for some NFL analysis in a dataframe where the relevant columns look like this:
- Randy Moss 12.9 2000
- Randy Moss 21.6 2000
- Randy Moss 4.0 2000
- Randy Moss 44.7 2000
- Randy Moss 25.8 2000
- Randy Moss 12.9 2000
it's not a list, it's a dataframe where a player's ("fname.1") fantasy stats for each game ("fp3") and year of the game ("year") are the columns in question. This data includes all years from 2000-2019.
I want to add a column which is the mean of all fantasy results for that year for that player. So, my wanted output in the example data (if randy moss only played 6 games) would add a column of the mean for each entry, like this:
- Randy Moss 12.9 2000 16.98333
- Randy Moss 21.6 2000 16.98333
- Randy Moss 4.0 2000 16.98333
- Randy Moss 44.7 2000 16.98333
- Randy Moss 25.8 2000 16.98333
- Randy Moss 12.9 2000 16.98333
I'm having trouble using a simple group_by() and summarize() formula because of needing a different mean per player for each year. I wrote a for loop that creates a list with the information I need, but I'm not sure how to add that into the original data or if there's an easier way to accomplish this...
mean_fantasy <- list()
for(y in 2000:2019) {
mean_fantasy[[y]] <- offense_test %>%
filter(year == y) %>%
group_by(fname.1) %>%
summarize(mean_fp3 = sum(fp3)/n(), games = n(), year = sum(year)/n())
}
Very new to R and this forum so hopefully this question/formatting makes sense