为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕雪6442864 2019-10-16 10:43:46
我想在data.table中创建一个新列,该列由一列的当前值和另一列的前一个值计算得出。是否可以访问以前的行?例如:> DT <- data.table(A=1:5, B=1:5*10, C=1:5*100)> DT   A  B   C1: 1 10 1002: 2 20 2003: 3 30 3004: 4 40 4005: 5 50 500> DT[, D := C + BPreviousRow] # What is the correct code here?正确答案应该是> DT   A  B   C   D1: 1 10 100  NA2: 2 20 200 2103: 3 30 300 3204: 4 40 400 4305: 5 50 500 540
查看完整描述

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更多信息。

查看历史记录以获取先前的答案。


查看完整回答
反对 回复 2019-10-16
?
忽然笑

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


查看完整回答
反对 回复 2019-10-16
?
拉丁的传说

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


查看完整回答
反对 回复 2019-10-16
  • 3 回答
  • 0 关注
  • 629 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信