[R] tapply output
Erik Iverson
eriki at ccbr.umn.edu
Wed Oct 6 21:24:26 CEST 2010
Hello,
You can use ddply from the very useful plyr package to do this.
There must be a way using "base R" functions, but plyr is
worth looking into in my opinion.
> install.packages("plyr")
> library(plyr)
> ddply(myData, .(class, group, name), function(x) mean(x$height))
class group name V1
1 0 A Tom 62.5
2 0 B Jane 58.5
3 1 A Enzo 66.5
4 1 B Mary 70.5
Geoffrey Smith wrote:
> Hello, I am having trouble getting the output from the tapply function
> formatted so that it can be made into a nice table. Below is my question
> written in R code. Does anyone have any suggestions? Thank you. Geoff
>
> #Input the data;
> name <- c('Tom', 'Tom', 'Jane', 'Jane', 'Enzo', 'Enzo', 'Mary', 'Mary');
> year <- c(2008, 2009, 2008, 2009, 2008, 2009, 2008, 2009);
> group <- c('A', 'A', 'B', 'B', 'A', 'A', 'B', 'B');
> class <- c(0, 0, 0, 0, 1, 1, 1, 1);
> height <- c(62, 63, 59, 58, 67, 66, 70, 71);
>
> #Combine the data into a data frame;
> myData <- data.frame(name, year, group, class, height);
> myData;
>
> #Calculate the mean of height by class, group, and name;
> tapply(myData$height, data.frame(myData$class, myData$group, myData$name),
> mean);
>
> #The raw output from the tapply function is fine, but I would;
> #really like the output to look like this;
> # class group name mean
> # 0 A Tom 62.5
> # 0 B Jane 58.5
> # 1 A Enzo 66.5
> # 1 B Mary 70.5
>
More information about the R-help
mailing list