4

I am trying to get the mean age of males and females with various health conditions from my data frame.

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

I can get the mean age individually using

mean(AgeAnalysis$Age [AgeAnalysis$Gender=="M" & AgeAnalysis$Gout=="TRUE"] , na.rm = TRUE)

but is there a more eloquent way to pull it all together into one table, such that the output of mean age is presented as

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

Thank you

Stewart Wiseman
  • 675
  • 2
  • 7
  • 14

2 Answers2

5

You could try the aggregate function:

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
sgibb
  • 25,396
  • 3
  • 68
  • 74
1

Here is a data.table solution

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


If you'd like it transposed, you can use:

# 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
Ricardo Saporta
  • 54,400
  • 17
  • 144
  • 178
  • Thanks, this did not run on my 32-bit version of R but it did on the 64-bit. Also I had to add na.rm=TRUE to the mean command but I am delighted to have a nice table. – Stewart Wiseman Jul 08 '13 at 20:52