通过模拟数据替换NA

时间:2013-02-01 13:39:34

标签: r na

在包含数字块和NA块的向量中,例如:

score <- c(0,1,2,3,4,NA,NA,0,-1,0,1,2,NA,NA,NA)

有没有办法模拟缺失值,通过在NA块之前的最新值中逐步向上计数?

所以最终会成为:

score.correct <- c(0,1,2,3,4,5,6,0,-1,0,1,2,3,4,5)

感谢您的帮助。

3 个答案:

答案 0 :(得分:4)

改编自Christos Hatzis on r-help

rna <- function(z) { 
  y <- c(NA, head(z, -1))
  z <- ifelse(is.na(z), y+1, z)
  if (any(is.na(z))) Recall(z) else z }

rna(score)
#[1]  0  1  2  3  4  5  6  0 -1  0  1  2  3  4  5

龙:

rna(c(NA,score))
Error: evaluation nested too deeply: infinite recursion / options(expressions=)?

rna(c(1,rep(NA,1e4)))
Error: evaluation nested too deeply: infinite recursion / options(expressions=)?

基准:

score2 <- 1:1e5
set.seed(42)
score2[sample(score2,10000)] <- NA
library(microbenchmark)
microbenchmark(rna(score2),incna(score2))

Unit: milliseconds
           expr      min        lq    median        uq       max
1 incna(score2)  2.93309  2.973896  2.990988  3.134501  5.360186
2   rna(score2) 50.42240 50.848931 51.228040 52.778043 56.856773

答案 1 :(得分:4)

Q + D,有一个循环,做了一些不必要的添加,但完成了工作:

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

如果第一项是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

答案 2 :(得分:2)

这是另一种方法:

library(zoo)
ifelse(is.na(score), na.locf(score) + sequence(rle(is.na(score))$l), score)
#  [1]  0  1  2  3  4  5  6  0 -1  0  1  2  3  4  5

显示[]表示NA位置的中间结果:

na.locf(score)
#  [1]  0  1  2  3  4  [4]  [4]  0 -1  0  1  2  [2]  [2]  [2]
sequence(rle(is.na(score))$l)
#  [1]  1  2  3  4  5  [1]  [2]  1  2  3  4  5  [1]  [2]  [3]
na.locf(score) + sequence(rle(is.na(score))$l)
#  [1]  1  3  5  7  9  [5]  [6]  1  1  3  5  7  [3]  [4]  [5]
ifelse(is.na(score), na.locf(score) + sequence(rle(is.na(score))$l), score)
#  [1]  0  1  2  3  4  [5]  [6]  0 -1  0  1  2  [3]  [4]  [5]