gpt4 book ai didi

r - data.table:一步一步进行分组,总和,命名新列和切片列

转载 作者:行者123 更新时间:2023-12-01 01:48:44 25 4
gpt4 key购买 nike

这似乎很容易,但是我一直无法弄清楚该怎么做。使用data.table我想用另一列C对一列A求和,而仅保留这两列。同时,我希望能够命名新列。我的尝试和期望的输出:

library(data.table)
dt <- data.table(A= c('a', 'b', 'b', 'c', 'c'), B=c('19', '20', '21', '22', '23'),
C=c(150,250,20,220,130))

# Desired Output - is there a way to do this in one step using data.table? #
new.data <- dt[, sum(C), by=A]
setnames(new.data,'V1', 'C.total')
new.data
A C.total
1: a 150
2: b 270
3: c 350

# Attempt 1: Problem is that columns B and C kept, extra rows kept #
new.data <- dt[, 'C.total' := sum(C), by=A]
new.data
A B C C.total
1: a 19 150 150
2: b 20 250 270
3: b 21 20 270
4: c 22 220 350
5: c 23 130 350

# Attempt 2: Problem is that new column not named #
new.data <- dt[, sum(C), by=A]
new.data
A V1
1: a 150
2: b 270
3: c 350

最佳答案

使用list(或.):

> dt[, list(C.total = sum(C)), by=A]
A C.total
1: a 150
2: b 270
3: c 350

关于r - data.table:一步一步进行分组,总和,命名新列和切片列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32124630/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com