compute means of a group by factor

前端 未结 4 617
太阳男子
太阳男子 2021-01-02 06:49

Is there a way that this can be improved, or done more simply?

means.by<-function(data,INDEX){
  b<-by(data,INDEX,function(d)apply(d,2,mean))
  return(         


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-02 07:34

    With plyr

    library(plyr)
    df <- ddply(x, .(id),function(x) data.frame(
    mean=mean(x$var)
    ))
    print(df)
    

    Update:

    data<-data.frame(I=as.factor(rep(letters[1:10],each=3)),x=rnorm(30),y=rbinom(30,5,.5))
    ddply(data,.(I), function(x) data.frame(x=mean(x$x), y=mean(x$y)))
    

    See, plyr is smart :)

    Update 2:

    In response to your comment, I believe cast and melt from the reshape package are much simpler for your purpose.

    cast(melt(data),I ~ variable, mean)
    

提交回复
热议问题