converting output of R's “by” command to data frame

前端 未结 3 1559
抹茶落季
抹茶落季 2021-01-18 05:42

I\'m trying to use R\'s by command to get column means for subsets of a data frame. For example, consider this data frame:

> z = data.frame(         


        
3条回答
  •  感情败类
    2021-01-18 06:29

    You can use ddply from plyr package

    library(plyr)
    ddply(z, .(labels), numcolwise(mean))
      labels data.1 data.2 data.3 data.4
    1      a    1.5    6.5   11.5   16.5
    2      b    3.0    8.0   13.0   18.0
    3      c    4.5    9.5   14.5   19.5
    

    Or aggregate from stats

    aggregate(z[,-1], by=list(z$labels), mean)
      Group.1 data.1 data.2 data.3 data.4
    1       a    1.5    6.5   11.5   16.5
    2       b    3.0    8.0   13.0   18.0
    3       c    4.5    9.5   14.5   19.5
    

    Or dcast from reshape2 package

    library(reshape2)
    dcast( melt(z), labels ~ variable, mean)
    

    Using sapply :

     t(sapply(split(z[,-1], z$labels), colMeans))
      data.1 data.2 data.3 data.4
    a    1.5    6.5   11.5   16.5
    b    3.0    8.0   13.0   18.0
    c    4.5    9.5   14.5   19.5
    

提交回复
热议问题