R, data.table: Sum all columns whose names are stored in a vector

主宰稳场 提交于 2019-12-31 02:33:07

问题


From a data.table d such as for example

require(data.table)
d = data.table(a = 1:4, b = 11:14, c = 21:24, group = c(1,1,2,2))

I would like to sum all variables which names are stored in the vector varsToSum by unique values of group.

varsToSum = c("a", "b")

For the above d and varsToSum, the expected outcome is

d[,list(a = sum(a), b = sum(b)),list(group)]

   group a  b
    1: 1 3 23
    2: 2 7 27

Related posts:

  • Select / assign to data.table variables which names are stored in a character vector

  • How to go from a vector of strings to a vector of quotes / names?


回答1:


d[, lapply(.SD, sum), by = group, .SDcols = varsToSum]

   group a  b
1:     1 3 23
2:     2 7 27


来源:https://stackoverflow.com/questions/50710266/r-data-table-sum-all-columns-whose-names-are-stored-in-a-vector

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