3 回答

TA貢獻1802條經驗 獲得超6個贊
使用v1.9.6中的shift()實現,這非常簡單。
DT[ , D := C + shift(B, 1L, type="lag")]
# or equivalently, in this case,
DT[ , D := C + shift(B)]
來自新聞:
新功能可shift()快速lead/lag實現vector,list,data.frames或data.tables。它采用的type參數可以是“ lag”(默認)或“ lead”。與:=或一起使用時,使用非常方便set()。例如:DT[, (cols) := shift(.SD, 1L), by=id]。請查看?shift更多信息。
查看歷史記錄以獲取先前的答案。

TA貢獻1806條經驗 獲得超5個贊
使用dplyr您可以做到:
mutate(DT, D = lag(B) + C)
這使:
# A B C D
#1: 1 10 100 NA
#2: 2 20 200 210
#3: 3 30 300 320
#4: 4 40 400 430
#5: 5 50 500 540

TA貢獻1789條經驗 獲得超8個贊
有幾個人回答了具體問題。請參閱以下代碼,以獲取在這種情況下可能有用的通用功能。不僅可以獲取上一行,還可以根據需要在“過去”或“未來”中進行任意多行。
rowShift <- function(x, shiftLen = 1L) {
r <- (1L + shiftLen):(length(x) + shiftLen)
r[r<1] <- NA
return(x[r])
}
# Create column D by adding column C and the value from the previous row of column B:
DT[, D := C + rowShift(B,-1)]
# Get the Old Faithul eruption length from two events ago, and three events in the future:
as.data.table(faithful)[1:5,list(eruptLengthCurrent=eruptions,
eruptLengthTwoPrior=rowShift(eruptions,-2),
eruptLengthThreeFuture=rowShift(eruptions,3))]
## eruptLengthCurrent eruptLengthTwoPrior eruptLengthThreeFuture
##1: 3.600 NA 2.283
##2: 1.800 NA 4.533
##3: 3.333 3.600 NA
##4: 2.283 1.800 NA
##5: 4.533 3.333 NA
- 3 回答
- 0 關注
- 710 瀏覽
添加回答
舉報