我有一個data.table
月度數據,而在另一個data.table
年度數據,現在我想的年度數據匹配的月度數據各自的觀察。我的方式是有效地複製data.table中的行嗎?
我的做法如下:複製的年度數據每個月,然後加入月報和年報數據。現在我有一個關於行重複的問題。我知道該怎麼做,但我不確定這是否是最好的辦法,所以有些意見會很棒。
這裏是我的年度數據的exemplatory 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)
DT1[DT]
ID MONTH values startMonth endMonth
a_1 1 10 1 3
a_1 2 10 1 3
a_1 3 10 1 3
a_2 3 11 3 6
[...]
最後加入是我想要的東西。然而,DT[, list(MONTH=startMonth:endMonth), by="ID"]
已經這樣做了我想要的一切,只是加入了其他列DT
,所以我在想,如果我能在我的代碼擺脫了最後三排的,即setkey
和join
操作。事實證明,你可以,只要做到以下幾點:
#2. Alternative: More intuitiv and just one line of code
DT[, list(MONTH=startMonth:endMonth, values, startMonth, endMonth), by="ID"]
ID MONTH values startMonth endMonth
a_1 1 10 1 3
a_1 2 10 1 3
a_1 3 10 1 3
a_2 3 11 3 6
...
然而,這只是工作,因爲我硬編碼列名到list
表達。在我的真實的數據,我不知道提前所有列的名稱,所以我在想,如果我能告訴data.table
返回,我計算如上圖所示,和DT
所有其他列的列MONTH
。 .SD
似乎是能夠做的伎倆,但:
DT[, list(MONTH=startMonth:endMonth, .SD), by="ID"]
Error in `[.data.table`(DT, , list(YEAR = startMonth:endMonth, .SD), by = "ID") :
maxn (4) is not exact multiple of this j column's length (3)
因此,要總結,我知道這是怎麼做了,但我只是想知道這是否是做的最好的方式,因爲我仍然在努力有一點與data.table
的語法有關,並且經常在帖子和wiki上讀到,有好的和壞的做事方式。另外,我不明白爲什麼我在使用.SD
時出現錯誤。我認爲這只是告訴data.table
你想要所有列的簡單方法。我錯過了什麼?
感謝。我跑它(v1.8.7),但我沒有看到'NA'。你有哪個版本? –
謝謝。我仍然看不到'NA',但現在我得到兩個相同的警告:'1:rep:數字表達式有2個元素:只有第一個使用' –
嘗試最新(796)作爲第一步,然後,請排除。 –