compute means of a group by factor

前端 未结 4 636
太阳男子
太阳男子 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:25

    Use only the generic function in R.

    >d=data.frame(type=as.factor(rep(c("A","B","C"),each=3)),
    x=rnorm(9),y=rgamma(9,2,1))
    > d
    type           x         y
    1    A -1.18077326 3.1428680
    2    A -0.91930418 4.4606603
    3    A  0.88345422 1.0979301
    4    B  0.06964133 1.1429911
    5    B -1.15380345 2.7609049
    6    B  1.13637202 0.6668986
    7    C -1.12052765 1.7352306
    8    C -1.34803630 2.3099202
    9    C -2.23135374 0.7244689
    >
    > cbind(lm(x~-1+type,data=d)$coef,lm(y~-1+type,data=d)$coef)
             [,1]     [,2]
    typeA -0.4055411 2.900486
    typeB  0.0174033 1.523598
    typeC -1.5666392 1.589873
    

提交回复
热议问题