gpt4 book ai didi

r - 两个因子的向量均值表

转载 作者:行者123 更新时间:2023-12-04 19:08:35 26 4
gpt4 key购买 nike

我正在学习 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com