我正在学习 R,我向你保证,我已经从高处和低处搜索过这个问题的答案。它是如此简单,但由于某种原因,我无法为我的生活弄明白!
我有一个包含一个数字向量和两个因子的数据框:
team.weight <- c(150,160,120,100) # player's weight
team.jersey <- factor(c("blue", "green", "blue", "blue")) # player's jersey color
team.sex <- factor(c("male", "female", "female", "male")) # player's sex
team <- data.frame(team.jersey, team.sex, team.weight)
我想显示一个表格(我忘记了它叫什么),它显示了两个因子表的每个级别组合的所有球员的平均体重,即 mean(team.weight)。
我可以手动执行此操作,但必须有更好的方法!
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])])
任何帮助将不胜感激。我知道答案很愚蠢,但我无法理解它是什么。