最佳答案
在data.frame
(或data.table
)中,我想要";填充转发";具有最接近的先前非NA值的NAS.下面是一个使用矢量(而不是data.frame
)的简单示例:
> y <- c(NA, 2, 2, NA, NA, 3, NA, 4, NA, NA)
我想要一个fill.NAs()
的函数,它允许我构造yy
,使得:
> yy
[1] NA NA NA 2 2 2 2 3 3 3 4 4
我需要对许多(总计约1 TB)小型_重复此操作ABC_0(约30-50 MB),其中行是NA,是其所有条目。解决这个问题的好方法是什么?
我提出的丑陋的解决方案使用了这个函数:
last <- function (x){
x[length(x)]
}
fill.NAs <- function(isNA){
if (isNA[1] == 1) {
isNA[1:max({which(isNA==0)[1]-1},1)] <- 0 # first is NAs
# can't be forward filled
}
isNA.neg <- isNA.pos <- isNA.diff <- diff(isNA)
isNA.pos[isNA.diff < 0] <- 0
isNA.neg[isNA.diff > 0] <- 0
which.isNA.neg <- which(as.logical(isNA.neg))
if (length(which.isNA.neg)==0) return(NULL) # generates warnings later, but works
which.isNA.pos <- which(as.logical(isNA.pos))
which.isNA <- which(as.logical(isNA))
if (length(which.isNA.neg)==length(which.isNA.pos)){
replacement <- rep(which.isNA.pos[2:length(which.isNA.neg)],
which.isNA.neg[2:max(length(which.isNA.neg)-1,2)] -
which.isNA.pos[1:max(length(which.isNA.neg)-1,1)])
replacement <- c(replacement, rep(last(which.isNA.pos), last(which.isNA) - last(which.isNA.pos)))
} else {
replacement <- rep(which.isNA.pos[1:length(which.isNA.neg)], which.isNA.neg - which.isNA.pos[1:length(which.isNA.neg)])
replacement <- c(replacement, rep(last(which.isNA.pos), last(which.isNA) - last(which.isNA.pos)))
}
replacement
}
功能fill.NAs
的使用方法如下:
y <- c(NA, 2, 2, NA, NA, 3, NA, 4, NA, NA)
isNA <- as.numeric(is.na(y))
replacement <- fill.NAs(isNA)
if (length(replacement)){
which.isNA <- which(as.logical(isNA))
to.replace <- which.isNA[which(isNA==0)[1]:length(which.isNA)]
y[to.replace] <- y[replacement]
}
输出
> y
[1] NA 2 2 2 2 3 3 3 4 4 4
...这似乎很有效。但是,伙计,它很丑吗?有什么建议?