我想以此为基础创建一个函数:
locf <- function(x) {
a <- x[1]
for (i in 2:length(x)) {
if (is.na(x[i])) x[i] <- a
else a <- x[i]
}
return(x)
}
这个函数只是 LOCF,我想为所有缺失的数据创建一个 LOCF 函数,为第一个缺失的观察创建一个 NOCB 函数。
我的数据:
data<-c(NA, 24.107, NA, 26.912, NA, 30.193, NA, 19.003, NA, NA, 28.578, NA, NA, 33.484, 32.952, 13.574, NA, NA, 38.782, NA, NA, NA, 28.804, NA, 27.042, NA, NA, NA, NA, 21.344, NA, 21.507, NA, NA, NA, 16.508, NA, NA, 14.015, 11.738, 15.055)
我想获得什么:
locf<-c(24.107, 24.107, 24.107, 26.912, 26.912, 30.193, 30.193, 19.003, 19.003, 19.003, 28.578, 28.578, 28.578, 33.484, 32.952, 13.574, 13.574, 13.574, 38.782, 38.782, 38.782, 38.782, 28.804, 28.804, 27.042, 27.042, 27.042, 27.042, 27.042, 21.344, 21.344, 21.507, 21.507, 21.507, 21.507, 16.508, 16.508, 16.508, 14.015, 11.738, 15.055)
先感谢您。