Here you go:
library(data.table)
Create the data:
Dt1 <- read.table(text="
date x
1/26/2010, 10
1/25/2010, 9
1/24/2010, 9
1/22/2010, 7
1/19/2010, 11", header=TRUE, stringsAsFactors=FALSE)
Dt2 <- read.table(text="
date
1/26/2010
1/23/2010
1/20/2010", header=TRUE, stringsAsFactors=FALSE)
Convert to data.table
, convert strings to dates, and set the data.table
key:
Dt1 <- data.table(Dt1)
Dt2 <- data.table(Dt2)
Dt1[, date:=as.Date(date, format=("%m/%d/%Y"))]
Dt2[, date:=as.Date(date, format=("%m/%d/%Y"))]
setkey(Dt1, date)
setkey(Dt2, date)
Join the tables, using roll=TRUE
:
Dt1[Dt2, roll=TRUE]
date x
[1,] 2010-01-20 11
[2,] 2010-01-23 7
[3,] 2010-01-26 10
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…