我正在学习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])])
任何帮助将不胜感激。我知道答案是愚蠢的,但我不明白这是什么。
最佳答案
tapply(team.weight, list(team$team.jersey, team$team.sex), mean)
# female male
# blue 120 125
# green 160 NA
关于r - 两个因素的向量均值表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18429883/