Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data.Table rolling join by group

Tags:

join

r

data.table

How can I find the last value, prior to test.day, for each (loc.x, loc.y) pair?

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")

Required output:

   loc.x loc.y value
1:     1     1     a
2:     1     2     f
3:     3     1     c
like image 954
Amitai Avatar asked Jan 13 '16 17:01

Amitai


Video Answer


1 Answers

Another option is to use the last function:

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

which gives:

   loc.x loc.y V1
1:     1     1  a
2:     1     2  f
3:     3     1  c
like image 111
Jaap Avatar answered Sep 21 '22 17:09

Jaap