Table of vector tools by two factors

I am studying R and I promise you that I was looking high and low to answer this question. It is so simple, but for some reason I cannot understand it for the life of me!

I have a dataframe containing one numeric vector and two factors:

team.weight <- c(150,160,120,100) # player weight team.jersey <- factor(c("blue", "green", "blue", "blue")) # player jersey color team.sex <- factor(c("male", "female", "female", "male")) # player sex team <- data.frame(team.jersey, team.sex, team.weight) 

I want to display a table (I forgot what it is called) that shows the average weight of all players, that is, the average (team.weight), for each combination of levels for two factor tables.

I can do it manually, but there must be a better way!

 mean(team.weight[c(team.jersey[1],team.sex[1])]) mean(team.weight[c(team.jersey[1],team.sex[2])]) mean(team.weight[c(team.jersey[1],team.sex[3])]) mean(team.weight[c(team.jersey[1],team.sex[4])]) mean(team.weight[c(team.jersey[2],team.sex[1])]) mean(team.weight[c(team.jersey[2],team.sex[2])]) mean(team.weight[c(team.jersey[2],team.sex[3])]) mean(team.weight[c(team.jersey[2],team.sex[4])]) mean(team.weight[c(team.jersey[3],team.sex[1])]) mean(team.weight[c(team.jersey[3],team.sex[2])]) mean(team.weight[c(team.jersey[3],team.sex[3])]) mean(team.weight[c(team.jersey[3],team.sex[4])]) mean(team.weight[c(team.jersey[4],team.sex[1])]) mean(team.weight[c(team.jersey[4],team.sex[2])]) mean(team.weight[c(team.jersey[4],team.sex[3])]) mean(team.weight[c(team.jersey[4],team.sex[4])]) 

Any help would be greatly appreciated. I know the answer is stupid, but I do not understand what it is.

+4
source share
2 answers
 tapply(team.weight, list(team$team.jersey, team$team.sex), mean) # female male # blue 120 125 # green 160 NA 
+2
source

Here is a plyr example:

 > library(plyr) > ddply(team,.(team.jersey,team.sex),summarize,avgWeight=mean(team.weight)) team.jersey team.sex avgWeight 1 blue female 120 2 blue male 125 3 green female 160 
+2
source

Source: https://habr.com/ru/post/1498836/


All Articles