[R] how to get the result in "short cut" manner?

Paul Hiemstra paul.hiemstra at knmi.nl
Wed Aug 17 13:38:07 CEST 2011


 On 08/16/2011 07:56 AM, Eik Vettorazzi wrote:
> Hi Lao,
> you tried to reinvent the wheel. Have a look at ?tapply
>
> tapply(sleep$extra,sleep$group,mean)
or take a look at the plyr package:

library(plyr)
data(sleep)
ddply(sleep, .(group), summarise, m = mean(extra))

cheers,
Paul

> Cheers
>
> Am 16.08.2011 09:41, schrieb Lao Meng:
>> Hi all:
>> My data:data(sleep)
>>
>> If I wanna calculate each group's extra,what I can do is:
>> #method1
>> attach(sleep)
>> mean(extra[group==1])
>> mean(extra[group==1])
>>
>>
>> #method2
>> result<-matrix(,0,2)
>> g<-split(sleep,sleep$group)
>> for(i in 1:length(g))
>> {
>> result<-rbind(result,data.frame(unique(g[[i]]$group),mean(g[[i]]$extra)))
>> }
>> colnames(result)<-c("name","mean")
>>
>> But the above 2 method is a little bit tedious.Is there a "short cut" manner
>> to get the same result?
>>
>> Thanks a lot!
>>
>> My best
>>
>> 	[[alternative HTML version deleted]]
>>
>> ______________________________________________
>> 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.


-- 
Paul Hiemstra, Ph.D.
Global Climate Division
Royal Netherlands Meteorological Institute (KNMI)
Wilhelminalaan 10 | 3732 GK | De Bilt | Kamer B 3.39
P.O. Box 201 | 3730 AE | De Bilt
tel: +31 30 2206 494

http://intamap.geo.uu.nl/~paul
http://nl.linkedin.com/pub/paul-hiemstra/20/30b/770



More information about the R-help mailing list