user30314
user30314

Reputation: 193

Make table using mean of a column in R

I have following data frame:

test <- data.frame(Gender = rep(c("M","F"),5), Death = c(1981:1985), Age = c(21:30))

and I wanted to know how can I reproduce following results using command table rather than ddply:

library(plyr)
ddply(test, c("Gender", "Death"), summarise, AgeMean = mean(Age))
  Death AgeMean
1  1981    23.5
2  1982    24.5
3  1983    25.5
4  1984    26.5
5  1985    27.5

Upvotes: 0

Views: 61

Answers (3)

Ajar
Ajar

Reputation: 1826

You can also do this using dplyr:

library(dplyr)

test %>%
  group_by(Death) %>%
  summarise(Age.mean = mean(Age))

I find dplyr's chaining syntax results in very readable code, but that's a personal preference.

Source: local data frame [5 x 2]

  Death Age.mean
1  1981     23.5
2  1982     24.5
3  1983     25.5
4  1984     26.5
5  1985     27.5

Upvotes: 0

rmbaughman
rmbaughman

Reputation: 921

Or you could also use summaryBy from the doBy package:

summaryBy(Age ~ Death,data=test,FUN=mean)
Death   Age.mean
1981    23.5
1982    24.5
1983    25.5
1984    26.5
1985    27.5

The variable(s) to the left of the ~ is the variable(s) you want to perform the function FUN= on (in this case mean) and the variable(s) to the right of the ~ is the new level of aggregation you want.

Upvotes: 2

Simon O&#39;Hanlon
Simon O&#39;Hanlon

Reputation: 59970

I think you mean aggregate...

aggregate( Age ~ Death , data = test , FUN = mean )
#  Death  Age
#1  1981 23.5
#2  1982 24.5
#3  1983 25.5
#4  1984 26.5
#5  1985 27.5

Upvotes: 2

Related Questions