Replace NA with last non-NA in data.table by using only data.table
问题 I want to replace NA values with last non-NA values in data.table and using data.table. I have one solution, but it's considerably slower than na.locf : library(data.table) library(zoo) library(microbenchmark) f1 <- function(x) { x[, X := na.locf(X, na.rm = F)] x } f2 <- function(x) { cond <- !is.na(x[, X]) x[, X := .SD[, X][1L], by = cumsum(cond)] x } m1 <- data.table(X = rep(c(NA,NA,1,2,NA,NA,NA,6,7,8), 100)) m2 <- data.table(X = rep(c(NA,NA,1,2,NA,NA,NA,6,7,8), 100)) microbenchmark(f1(m1),