In a vector containing blocks of numbers and blocks of NAs, such as:
score <- c(0,1,2,3,4,NA,NA,0,-1,0,1,2,NA,NA,NA)
is there a way to simulate missing values by counting upwards in steps of one from the latest value before the block of NAs?
So it would end up being:
score.correct <- c(0,1,2,3,4,5,6,0,-1,0,1,2,3,4,5)
Thanks for any help.
Q+D, has a loop, does some unneccessary addition, but does the job:
incna <- function(s){
while(any(is.na(s))){
ina = which(is.na(s))
s[ina]=s[ina-1]+1
}
s
}
> score
[1] 0 1 2 3 4 NA NA 0 -1 0 1 2 NA NA NA
> incna(score)
[1] 0 1 2 3 4 5 6 0 -1 0 1 2 3 4 5
Fails with only a warning if first item is NA:
> score
[1] NA 1 2 3 4 NA NA 0 -1 0 1 2 NA NA NA
> incna(score)
[1] 5 1 2 3 4 5 3 0 -1 0 1 2 3 4 5
Warning message:
In s[ina] = s[ina - 1] + 1 :
number of items to replace is not a multiple of replacement length
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With