我想对变量进行最后一次观察,但最多只能观察2次。也就是说,对于3个或更多NA的数据间隙,我只会在接下来的2个观察中向前推进最后一个观察,并将其余的观察结果保留为NA。
如果我使用zoo::na.locf
执行此操作,则maxgap
参数意味着如果间隙大于2,则不替换NA。甚至不是最后的2.有没有其他选择?
x <- c(NA,3,4,5,6,NA,NA,NA,7,8)
zoo::na.locf(x, maxgap = 2) # Doesn't replace the first 2 NAs of after the 6 as the gap of NA is 3.
Desired_output <- c(NA,3,4,5,6,6,6,NA,7,8)
使用基数R的解决方案:
ave(x, cumsum(!is.na(x)), FUN = function(i){ i[1:pmin(length(i), 3)] <- i[1]; i })
# [1] NA 3 4 5 6 6 6 NA 7 8
cumsum(!is.na(x))
将每次运行的NA
s与最近的非NA
值组合在一起。
function(i){ i[1:pmin(length(i), 3)] <- i[1]; i }
将每组的前两个NA
s转换为该组的主要非NA
值。
首先将na.locf0
与maxgap = 2
一起应用x0
,并使用data.table包中的g
定义分组变量rleid
。对于每个这样的组,使用ave
来应用keeper
,如果该组都是NA,则将其替换为c(1,1,NA,...,NA),否则输出全1。乘以na.locf0(x)
。
library(data.table)
library(zoo)
mg <- 2
x0 <- na.locf0(x, maxgap = mg)
g <- rleid(is.na(x0))
keeper <- function(x) if (all(is.na(x))) ifelse(seq_along(x) <= mg, 1, NA) else 1
na.locf0(x) * ave(x0, g, FUN = keeper)
## [1] NA 3 4 5 6 6 6 NA 7 8