10

在包含数字块和 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)

谢谢你的帮助。

4

3 回答 3

4

改编自Christos Hatzis 上 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
于 2013-02-01T13:51:30.197 回答
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
于 2013-02-01T13:52:32.177 回答
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]
于 2013-02-01T18:26:57.197 回答