在R中需要满足2个条件时计算平均值

时间:2013-07-07 14:40:28

标签: r

我试图从我的数据框架中获得具有各种健康状况的男性和女性的平均年龄。

AgeAnalyisi$Age     num
AgeAnalyisi$Gout        logical
AgeAnalyisi$Arthritis   logical
AgeAnalyisi$Vasculitis  logical
etc
AgeAnalysis$Gender      Factor w/ 2 levels

我可以单独使用

获得平均年龄
mean(AgeAnalysis$Age [AgeAnalysis$Gender=="M" & AgeAnalysis$Gout=="TRUE"] , na.rm = TRUE)

但是有一种更有说服力的方法将它们全部拉到一个表中,这样平均年龄的输出就会显示为

          Male  Female
Gout        x   x
Arthritis   x   x
Vasculitis  x   x
etc         x   x

谢谢

2 个答案:

答案 0 :(得分:4)

您可以尝试aggregate功能:

df <- data.frame(value=1:10, letter=rep(LETTERS[1:2], each=5), group=rep(c(1,2), times=5))
aggregate(value ~ letter * group, data=df, FUN=mean)
#  letter group value
#1      A     1     3
#2      B     1     8
#3      A     2     3
#4      B     2     8

答案 1 :(得分:1)

这是一个data.table解决方案

library(data.table)
AgeAnalyisis.DT <- data.table(AgeAnalyisis)

AgeAnalyisis.DT[, lapply(.SD[, !"Age", with=FALSE], function(x) mean(Age[x]))
                , by=Gender]

   Gender     Gout Arthritis Vasculitis
1:      F 54.58333  52.00000   55.81818
2:      M 50.09091  52.69231   52.40000


如果您想要转置,可以使用:

# Save the results
res <- AgeAnalyisis.DT[, lapply(.SD[, !"Age", with=FALSE], function(x) mean(Age[x]))
                       , by=Gender]
# Transpose, and assign Gender as column names
results <- t(res[,!"Gender", with=FALSE])
colnames(results) <- res[, Gender]

results
#                   F        M
# Gout       58.30263 57.50328
# Arthritis  66.00217 67.91978
# Vasculitis 59.76155 57.86556