#Calculate the Mean by Group average
#create data frame
df <- data.frame(team=c('a', 'a', 'b', 'b', 'b', 'c', 'c'),
pts=c(5, 8, 14, 18, 5, 7, 7),
rebs=c(8, 8, 9, 3, 8, 7, 4))
df
## team pts rebs
## 1 a 5 8
## 2 a 8 8
## 3 b 14 9
## 4 b 18 3
## 5 b 5 8
## 6 c 7 7
## 7 c 7 4
###method_1 aggregate
#find mean points scored by team
aggregate(df[,2:3], list(team = df$team), FUN=mean)
## team pts rebs
## 1 a 6.50000 8.000000
## 2 b 12.33333 6.666667
## 3 c 7.00000 5.500000
###method_2 '
library(dplyr)
##
## 载入程辑包:'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
#find mean points scored by team
df %>%
group_by(team) %>%
summarise_at(vars(pts), list(name = mean))
## # A tibble: 3 x 2
## team name
## <chr> <dbl>
## 1 a 6.5
## 2 b 12.3
## 3 c 7
#ref https://www.statology.org/r-mean-by-group/