4

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

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

谢谢

4

2 回答 2

5

你可以试试这个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
于 2013-07-07T14:44:47.667 回答
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
于 2013-07-07T15:39:27.433 回答