1) 定义lastEpos,其中给定i 返回最后一个E 在前i 行中的位置,并将其应用于每个行号:
lastEpos <- function(i) tail(which(tempDT$colA[1:i] == "E"), 1)
tempDT[, lags := .I - shift(sapply(.I, lastEpos))]
这里有一些变化:
2) i-1 在此变体中,lastEpos 返回最后一个E 在前i-1 行中的位置,而不是i:
lastEpos <- function(i) tail(c(NA, which(tempDT$colA[seq_len(i-1)] == "E")), 1)
tempDT[, lags := .I - sapply(.I, lastEpos)]
3) 位置 类似于 (2) 但使用Position:
lastEpos <- function(i) Position(c, tempDT$colA[seq_len(i-1)] == "E", right = TRUE)
tempDT[, lags := .I - sapply(.I, lastEpos)]
4) 滚动应用
library(zoo)
w <- lapply(1:nrow(tempDT), function(i) -rev(seq_len(i-1)))
tempDT[, lags := .I - rollapply(colA == "E", w, Position, f = c, right = TRUE)]
5) sqldf
library(sqldf)
sqldf("select a.colA, a.rowid - b.rowid lags
from tempDT a left join tempDT b
on b.rowid < a.rowid and b.colA = 'E'
group by a.rowid")