I have a dataframe that contains ratings for games and they are divided into categories and whether or not the game is a solo game or not.
category <- c("Party","Adventure","Puzzle","Party","Adventure","Puzzle","Party","Adventure","Puzzle","Party","Adventure","Puzzle","Party","Adventure","Puzzle","Party","Adventure","Puzzle")
solo <- c("solo","solo","solo","double","double","double","solo","solo","solo","double","double","double","solo","solo","solo","double","double","double")
rating <- c(8,7,6,5,3,3,2,1,10,3,4,5,6,3,2,1,3,1)
df <- as.data.frame(rating)
df$solo <- solo
df$category <- category
My question is, how do I get the average rating for each category that belongs to each grouping (solo/double)? Solo Party and Double Party should have different avg ratings for example.
CodePudding user response:
After grouping by 'category' and 'solo', get the mean
library(dplyr)
df <- df %>%
group_by(category, solo) %>%
mutate(avg = mean(rating, na.rm = TRUE)) %>%
ungroup
-output
df
# A tibble: 18 × 4
rating solo category avg
<dbl> <chr> <chr> <dbl>
1 8 solo Party 5.33
2 7 solo Adventure 3.67
3 6 solo Puzzle 6
4 5 double Party 3
5 3 double Adventure 3.33
6 3 double Puzzle 3
7 2 solo Party 5.33
8 1 solo Adventure 3.67
9 10 solo Puzzle 6
10 3 double Party 3
11 4 double Adventure 3.33
12 5 double Puzzle 3
13 6 solo Party 5.33
14 3 solo Adventure 3.67
15 2 solo Puzzle 6
16 1 double Party 3
17 3 double Adventure 3.33
18 1 double Puzzle 3