How to na.locf in R without using additional packages [duplicate]

老子叫甜甜 提交于 2020-01-10 05:57:58

问题


Given a vector such as (say) c(2,NA,5,NA,NA,1,NA) the problem is to "last observation carry forward" resulting in vector c(2,2,5,5,5,1,1).

As answered here, na.locf from the zoo package can do this. However, given the simplicity of the problem, and the fact that this is to be performed many times from a "blank" R environment, I would like to do this without loading packages. Is there a way to do it simply and quickly using just basic R? (The vector may be long and may contain many consecutive NAs.)


回答1:


Extracted from zoo::na.locf.default

fillInTheBlanks <- function(S) {
  L <- !is.na(S)
  c(S[L][1], S[L])[cumsum(L)+1]
}

See also here.




回答2:


This is one way using rle:

x <- c(2,NA,5,NA,NA,1,NA) 
x[is.na(x)] <- Inf
x[is.infinite(x)] <- with(rle(x), 
    rep(values[which(is.infinite(values)) - 1], lengths[is.infinite(values)])
)
# [1] 2 2 5 5 5 1 1


来源:https://stackoverflow.com/questions/19838735/how-to-na-locf-in-r-without-using-additional-packages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!