gpt4 book ai didi

r - 各组最近值的总和

转载 作者:行者123 更新时间:2023-12-03 09:12:23 25 4
gpt4 key购买 nike

对于我的每一行数据,我想计算最近 value 的总和每个group :

dt = data.table(group = c('a','b','a','a','b','a'),
value = c(10, 5, 20, 15, 15, 10),
desired = c(10, 15, 25, 20, 30, 25))
# group value desired
#1: a 10 10
#2: b 5 15
#3: a 20 25 # latest value of a is 20, of b is 5
#4: a 15 20 # latest value of a is 15, of b is 5
#5: b 15 30
#6: a 10 25
desired column 是我想要实现的,我可以用一个简单的循环来做到这一点,但是我的数据非常大,有很多行和组(1M+ 行,1000+ 组)。
for (i in seq_len(nrow(dt))) {
# can use `set` to make this faster, but still too slow
# this is just to illustrate *a* solution
dt[i, desired1 := dt[1:i, value[.N], by = group][, sum(V1)]]
}

最佳答案

来自@eddi(在评论下)的更简单的逻辑减少了如下所示的迂回:

dt[, incr := diff(c(0, value)), by = group][, ans := cumsum(incr)]

不确定它如何扩展到更多组,但这里有一个包含 3 个组的示例数据:
# I hope I got the desired output correctly
require(data.table)
dt = data.table(group = c('a','b','c','a','a','b','c','a'),
value = c(10, 5, 20, 25, 15, 15, 30, 10),
desired = c(10, 15, 35, 50, 40, 50, 60, 55))

添加 rleid :
dt[, id := rleid(group)]

为每个 group, id 提取最后一行:
last = dt[, .(value=value[.N]), by=.(group, id)]
last会有独特的 id .现在的想法是获得每个 id 的增量,然后加入+更新回来。
last = last[, incr := value - shift(value, type="lag", fill=0L), by=group
][, incr := cumsum(incr)-value][]

立即加入 + 更新:
dt[last, ans := value + i.incr, on="id"][, id := NULL][]
# group value desired ans
# 1: a 10 10 10
# 2: b 5 15 15
# 3: c 20 35 35
# 4: a 25 50 50
# 5: a 15 40 40
# 6: b 15 50 50
# 7: c 30 60 60
# 8: a 10 55 55

我还不确定这在哪里/是否会中断..现在会仔细看看。我立即写了它,以便有更多的人关注它。

使用 David 的解决方案比较 500 个组和 10,000 行:
require(data.table)
set.seed(45L)
groups = apply(matrix(sample(letters, 500L*10L, TRUE), ncol=10L), 1L, paste, collapse="")
uniqueN(groups) # 500L
N = 1e4L
dt = data.table(group=sample(groups, N, TRUE), value = sample(100L, N, TRUE))

arun <- function(dt) {

dt[, id := rleid(group)]
last = dt[, .(value=value[.N]), by=.(group, id)]
last = last[, incr := value - shift(value, type="lag", fill=0L), by=group
][, incr := cumsum(incr)-value][]
dt[last, ans := value + i.incr, on="id"][, id := NULL][]
dt$ans
}

david <- function(dt) {
dt[, indx := .I]
res <- dcast(dt, indx ~ group)
for (j in names(res)[-1L])
set(res, j = j, value = res[!is.na(res[[j]])][res, on = "indx", roll = TRUE][[j]])
rowSums(as.matrix(res)[, -1], na.rm = TRUE)

}

system.time(ans1 <- arun(dt)) ## 0.024s
system.time(ans2 <- david(dt)) ## 38.97s
identical(ans1, as.integer(ans2))
# [1] TRUE

关于r - 各组最近值的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37732135/

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