以下是您的问题的可能解决方案dplyr
(首先,因为这就是你尝试过的),然后是data.table
也base R
解决方案:
dplyr:
cols <- lapply(names(data)[-(1:2)], as.name)
names(cols) <- paste0(names(data)[-(1:2)], "_tot")
data %>% group_by(region) %>% mutate_each_q(funs(sum), cols)
假设除前两列外的每一列都是月度数据。按行解释:
- we use
as.name
and lapply
生成我们想要的列名称列表mutate
作为符号
- 我们为 1 中的符号列表赋予我们想要的新名称(即 Month_tot)。
- 我们使用
mutate_each_q
(作为。。而被知道mutate_each_
in dplyr 0.3.0.2
) 申请sum
到我们在 1. 和 2 中创建的表达式列表。
这是(示例)结果:
Source: local data frame [50 x 6]
Groups: region
biz region june july june_tot july_tot
1 shipping mideast 17 124 780 3339
2 telco americas 11 101 465 2901
3 telco mideast 27 131 780 3339
4 tech americas 24 135 465 2901
... rows omitted
数据表:
new.names <- paste0(tail(names(data), 2L), "_tot") # Make new names
data.table(data)[,
(new.names):=lapply(.SD, sum), # `lapply` `sum` to the selected columns (those in .SD), and assign to `new.names` columns
by=region, .SDcols=-1 # group by `region`, and exclude first column from `.SD` (note `region` is excluded as well by reason of being in `by`
][] # extra `[]` just to force printing
在这里,类似的逻辑,除了我们使用特殊的.SD
代表每列的对象data.table
我们没有分组依据。
base:
do.call(
cbind,
list(
data,
setNames(
lapply(data[-(1:2)], function(x) ave(x, data$region, FUN=sum)),
paste0(names(data[-(1:2)]), "_tot")
) ) )
这里我们使用ave
要计算每个区域的总和,请使用lapply
申请ave
到每一列,并使用do.call(cbind, ...)
重建最终的数据帧。