在R data.table计算中使用上一行的值

我想在data.table中创建一个新列,该列由一列的当前值和另一列的前一个值计算得出。是否可以访问以前的行?


例如:


> DT <- data.table(A=1:5, B=1:5*10, C=1:5*100)

> DT

   A  B   C

1: 1 10 100

2: 2 20 200

3: 3 30 300

4: 4 40 400

5: 5 50 500

> DT[, D := C + BPreviousRow] # What is the correct code here?

正确答案应该是


> DT

   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


慕雪6442864
浏览 623回答 3
3回答

呼啦一阵风

使用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更多信息。查看历史记录以获取先前的答案。

忽然笑

使用dplyr您可以做到:mutate(DT, D = lag(B) + C)这使:#&nbsp; &nbsp;A&nbsp; B&nbsp; &nbsp;C&nbsp; &nbsp;D#1: 1 10 100&nbsp; NA#2: 2 20 200 210#3: 3 30 300 320#4: 4 40 400 430#5: 5 50 500 540

拉丁的传说

有几个人回答了具体问题。请参阅以下代码,以获取在这种情况下可能有用的通用功能。不仅可以获取上一行,还可以根据需要在“过去”或“未来”中进行任意多行。rowShift <- function(x, shiftLen = 1L) {&nbsp; r <- (1L + shiftLen):(length(x) + shiftLen)&nbsp; r[r<1] <- NA&nbsp; 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,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;eruptLengthTwoPrior=rowShift(eruptions,-2),&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;eruptLengthThreeFuture=rowShift(eruptions,3))]##&nbsp; &nbsp;eruptLengthCurrent eruptLengthTwoPrior eruptLengthThreeFuture##1:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 3.600&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; NA&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 2.283##2:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 1.800&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; NA&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 4.533##3:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 3.333&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;3.600&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;NA##4:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 2.283&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;1.800&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;NA##5:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 4.533&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;3.333&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;NA
打开App,查看更多内容
随时随地看视频慕课网APP