如何在test.day之前找到每个(loc.x,loc.y)对的最后一个值?
dt <- data.table( loc.x = as.integer(c(1,1,3,1)),loc.y = as.integer(c(1,2,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
解决方法
另一个选择是使用最后一个函数:
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