将NA替换为具有限制的先前值 [英] Replace NA with previous value with limit
本文介绍了将NA替换为具有限制的先前值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用最新的非NA值替换向量中最多n
个NA值.
I would like to replace up to n
NA values in vector with latest non-NA value.
例如,如果:
a <- c(1,NA,NA,NA,NA,NA,2,NA,1,NA,NA,NA)
n <- 2
我想获得:
c(1,1,1,NA,NA,NA,2,2,1,1,1,NA)
n
是可以用给定元素替换的最大NA值.
n
is maximum number of NA values that can be replaced by given element).
我知道na.locf()
函数,但是我不知道如何设置限制n
.有可能做到吗?
I know na.locf()
function, but I don't know how to set the limit n
. Is it possible to do it?
推荐答案
以下是使用na.locf
和rle
library(zoo)
r <- rle(is.na(a))
a <- na.locf(a)
is.na(a) <- sequence(r$lengths) > n & rep(r$values, r$lengths)
a
# [1] 1 1 1 NA NA NA 2 2 1 1 1 NA
因此,这里我首先计算a
中元素的游程长度(包括NA条目),然后使用na.locf
替换所有NA,最后将这些元素放回到游程长度大于n
的NA处.元素是NA
.
So here I first computed the run lengths of elements in a
(including the NA entries), then replaced all NA's using na.locf
and finally turned those elements back to NA's where the run lengths were greater than n
and the elements were NA
.
这篇关于将NA替换为具有限制的先前值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文