我有一个月度数据data.table和另一个年度数据data.table,现在我想将年度数据与月度数据中的相应观察值相匹配.
我的方法如下:复制每个月的年度数据,然后加入月度和年度数据.现在我有一个关于行重复的问题.我知道怎么做,但我不确定这是不是最好的方法,所以有些意见会很棒.
以下是data.table DT我的年度数据的示例以及我目前的复制方式:
library(data.table)
DT <- data.table(ID = paste(rep(c("a", "b"), each=3), c(1:3, 1:3), sep="_"),
values = 10:15,
startMonth = seq(from=1, by=2, length=6),
endMonth = seq(from=3, by=3, length=6))
DT
ID values startMonth endMonth
[1,] a_1 10 1 3
[2,] a_2 11 3 6
[3,] a_3 12 5 9
[4,] b_1 13 7 12
[5,] b_2 14 9 15
[6,] b_3 15 11 18
#1. Alternative
DT1 <- DT[, list(MONTH=startMonth:endMonth), by="ID"]
setkey(DT, ID)
setkey(DT1, ID) …Run Code Online (Sandbox Code Playgroud)