Sum of rows based on column value

风流意气都作罢 提交于 2019-11-27 06:41:21
ddply(df, "X1", numcolwise(sum))

see ?numcolwise for details and examples.

aggregate can easily do this with the formula interface:

aggregate(. ~ X1, data=df, FUN=sum)
##   X1 X2 X3
## 1  a  4  7
## 2  b  5  3
## 3  c  8  7

Equivalently:

aggregate(cbind(X2, X3) ~ X1, data=df, FUN=sum)

aggregate is a great function for these sorts of things:

aggregate(df[,-1],df["X1"],sum)

  X1 X2 X3
1  a  4  7
2  b  5  3
3  c  8  7

And a base R version of the numcolwise method from plyr:

aggregate(df[,sapply(df,is.numeric)],df["X1"],sum)

A data.table solution for memory efficiency and coding elegance

library(data.table)
DT <- data.table(df)


DT[, lapply(.SD, sum), by = X1]

.SD is the subset of the data.table for each group defined by the values of X1. There are 3 helpful vignettes associated with the data.table package.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!