How to get the mean value of each column, group by sth?

后端 未结 2 1742
自闭症患者
自闭症患者 2021-01-22 07:26

I am using R. I have a dataset.

group attribute1 attribute2 attribute3
A     1          2          3
A     2          3          4
B     2          4          2
         


        
相关标签:
2条回答
  • 2021-01-22 08:13
    > mydf <- data.frame(group=c('a','a','b','b'), a1=c(1,1,2,2), a2=c(2,3,4,2), a3=c(3,4,2,1))
    > aggregate(. ~ group, mydf, mean)
        group a1  a2  a3
    1       a  1 2.5 3.5
    2       b  2 3.0 1.5
    

    or using plyr:

    ddply(mydf, "group", colwise(mean))
    
    0 讨论(0)
  • 2021-01-22 08:18

    Using data.table:

    library(data.table)
    mydf <- data.frame(group=c('a','a','b','b'), a1=c(1,1,2,2), a2=c(2,3,4,2), a3=c(3,4,2,1))
    my.dt <- data.table(mydf)
    my.dt[, lapply(.SD, mean), by = group]
    
       group a1  a2  a3
    1:     a  1 2.5 3.5
    2:     b  2 3.0 1.5
    
    0 讨论(0)
提交回复
热议问题