sum multiple columns by group with tapply

前端 未结 3 1963
北荒
北荒 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-15 23:49

    You're looking for by. It uses the INDEX in the way that you assumed tapply would, by row.

    by(df.1, df.1$state, function(x) colSums(x[,3:5]))
    

    The problem with your use of tapply is that you were indexing the data.frame by column. (Because data.frame is really just a list of columns.) So, tapply complained that your index didn't match the length of your data.frame which is 5.

提交回复
热议问题