gpt4 book ai didi

r - 数据表按组滚动连接

转载 作者:行者123 更新时间:2023-12-04 09:58:40 28 4
gpt4 key购买 nike

如何为每对(loc.xloc.y)对找到test.day 之前的最后一个

dt <- data.table( 
loc.x = as.integer(c(1, 1, 3, 1, 3, 1)),
loc.y = as.integer(c(1, 2, 1, 2, 1, 2)),
time = as.IDate(c("2015-03-11", "2015-05-10", "2015-09-27",
"2015-11-25", "2014-09-13", "2015-08-19")),
value = letters[1:6]
)

setkey(dt, loc.x, loc.y, time)
test.day <- as.IDate("2015-10-01")

要求的输出:
   loc.x loc.y value
1: 1 1 a
2: 1 2 f
3: 3 1 c

最佳答案

另一种选择是使用last函数:

dt[, last(value[time < test.day]), by = .(loc.x, loc.y)]

这使:
   loc.x loc.y V1
1: 1 1 a
2: 1 2 f
3: 3 1 c

关于r - 数据表按组滚动连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34772664/

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