第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

慕雪6442864 2019-10-16 10:43:46
我想在data.table中創(chuàng)建一個新列,該列由一列的當(dāng)前值和另一列的前一個值計算得出。是否可以訪問以前的行?例如:> 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?正確答案應(yīng)該是> 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 回答

?
呼啦一陣風(fēng)

TA貢獻(xiàn)1802條經(jīng)驗 獲得超6個贊

使用v1.9.6中的shift()實現(xiàn),這非常簡單。


DT[ , D := C + shift(B, 1L, type="lag")]

# or equivalently, in this case,

DT[ , D := C + shift(B)]

來自新聞:


新功能可shift()快速lead/lag實現(xiàn)vector,list,data.frames或data.tables。它采用的type參數(shù)可以是“ lag”(默認(rèn))或“ lead”。與:=或一起使用時,使用非常方便set()。例如:DT[, (cols) := shift(.SD, 1L), by=id]。請查看?shift更多信息。

查看歷史記錄以獲取先前的答案。


查看完整回答
反對 回復(fù) 2019-10-16
?
忽然笑

TA貢獻(xiàn)1806條經(jīng)驗 獲得超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


查看完整回答
反對 回復(fù) 2019-10-16
?
拉丁的傳說

TA貢獻(xiàn)1789條經(jīng)驗 獲得超8個贊

有幾個人回答了具體問題。請參閱以下代碼,以獲取在這種情況下可能有用的通用功能。不僅可以獲取上一行,還可以根據(jù)需要在“過去”或“未來”中進(jìn)行任意多行。


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


查看完整回答
反對 回復(fù) 2019-10-16
  • 3 回答
  • 0 關(guān)注
  • 715 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號