Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace NAs by simulating data

Tags:

r

na

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.

like image 564
Lucy Vanes Avatar asked Feb 01 '13 13:02

Lucy Vanes


1 Answers

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
like image 60
Spacedman Avatar answered Sep 20 '22 13:09

Spacedman