sum multiple columns by group with tapply

前端 未结 3 1966
北荒
北荒 2020-12-15 23:03

I wanted to sum individual columns by group and my first thought was to use tapply. However, I cannot get tapply to work. Can tapply

3条回答
  •  悲&欢浪女
    2020-12-16 00:06

    tapply works on a vector, for a data.frame you can use by (which is a wrapper for tapply, take a look at the code):

    > by(df.1[,c(3:5)], df.1$state, FUN=colSums)
    df.1$state: AA
      apples cherries    plums 
         111      222      333 
    ------------------------------------------------------------------------------------- 
    df.1$state: BB
      apples cherries    plums 
        -111     -222     -333 
    

提交回复
热议问题