I have a fairly big vector (>500,000 in length). It contains a bunch of NA
interspersed with 1
and it is always guaranteed that it begins with 1
.
I would like to replace some of the NA
in v1
with 1
, based on a comparison operation on contiguous indices of another vector v2
(of same length as v1
).
Is there an efficient way of doing this in vectorized notation so that looping is done in a low-level implementation? Maybe using ifelse
?
Reproducible example below:
v1<-c(1,NA,NA,NA,1,NA,NA,NA,NA,NA,1,NA,NA,1,NA,1,NA,NA,NA,NA,NA,NA,NA,NA,NA,1)
v2<-c(10,10,10,9,10,9,9,9,9,9,10,10,10,11,8,12,12,12,12,12,12,12,12,12,12,13)
# goal is to fill through v1 in such a way that whenever
# v1[i] == NA and v1[i-1] == 1 and v2[i] == v2[i-1], then v1[i] == 1
MM<-data.frame(v1,v2)
for (i in 2:length(v1)){
# conditions: v1[i-1] == 1; v1[i]==NA; v2[i]==v2[i-1]
if (!is.na(v1[i-1]) && is.na(v1[i]) && v2[i]==v2[i-1]){
v1[i]<-1
}
}
MM$v1_altered<-v1
MM