[R] tapply output

jim holtman jholtman at gmail.com
Thu Oct 7 14:04:30 CEST 2010


You can also use sqldf:


> require(sqldf)
> sqldf("select class, `group`, name, avg(height)
+     from myData
+     group by class, 'group', name")
  class group name avg(height)
1     0     B Jane        58.5
2     0     A  Tom        62.5
3     1     A Enzo        66.5
4     1     B Mary        70.5
>


On Thu, Oct 7, 2010 at 4:49 AM, Peter Ehlers <ehlers at ucalgary.ca> wrote:
> On 2010-10-06 13:24, Erik Iverson wrote:
>>
>> 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
>
> Or use summarize:
>
>  >  ddply(myData, .(class, group, name), summarize, mht = mean(height))
>
>  -Peter Ehlers
>
>>
>> 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
>>>
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem that you are trying to solve?



More information about the R-help mailing list