用最新的非NA值替换NA值

208
data.frame(或 data.table)中,我想用最近的非 NA 值填充 NA。 以下是一个简单的示例,使用向量(而不是 data.frame):
> y <- c(NA, 2, 2, NA, NA, 3, NA, 4, NA, NA)

我希望有一个名为fill.NAs()的函数,可以帮助我构建yy,使得:

> yy
[1] NA NA NA  2  2  2  2  3  3  3  4  4

我需要为许多(总共约1TB)小型数据框(约30-50MB)重复此操作,其中如果一行的所有条目都是NA,则该行为NA。有什么好的方法来解决这个问题?

我想到了一个丑陋的解决方案,使用了这个函数:

last <- function (x){
    x[length(x)]
}    

fill.NAs <- function(isNA){
if (isNA[1] == 1) {
    isNA[1:max({which(isNA==0)[1]-1},1)] <- 0 # first is NAs 
                                              # can't be forward filled
}
isNA.neg <- isNA.pos <- isNA.diff <- diff(isNA)
isNA.pos[isNA.diff < 0] <- 0
isNA.neg[isNA.diff > 0] <- 0
which.isNA.neg <- which(as.logical(isNA.neg))
if (length(which.isNA.neg)==0) return(NULL) # generates warnings later, but works
which.isNA.pos <- which(as.logical(isNA.pos))
which.isNA <- which(as.logical(isNA))
if (length(which.isNA.neg)==length(which.isNA.pos)){
    replacement <- rep(which.isNA.pos[2:length(which.isNA.neg)], 
                                which.isNA.neg[2:max(length(which.isNA.neg)-1,2)] - 
                                which.isNA.pos[1:max(length(which.isNA.neg)-1,1)])      
    replacement <- c(replacement, rep(last(which.isNA.pos), last(which.isNA) - last(which.isNA.pos)))
} else {
    replacement <- rep(which.isNA.pos[1:length(which.isNA.neg)], which.isNA.neg - which.isNA.pos[1:length(which.isNA.neg)])     
    replacement <- c(replacement, rep(last(which.isNA.pos), last(which.isNA) - last(which.isNA.pos)))
}
replacement
}

函数fill.NAs的用法如下:

y <- c(NA, 2, 2, NA, NA, 3, NA, 4, NA, NA)
isNA <- as.numeric(is.na(y))
replacement <- fill.NAs(isNA)
if (length(replacement)){
which.isNA <- which(as.logical(isNA))
to.replace <- which.isNA[which(isNA==0)[1]:length(which.isNA)]
y[to.replace] <- y[replacement]
} 

输出

> y
[1] NA  2  2  2  2  3  3  3  4  4  4

...看起来好像能用。但是,天啊,它太丑了!有什么建议吗?


1
从其他问题中,我认为你现在已经在data.table中找到了roll=TRUE - Matt Dowle
22个回答

205
你可能想要使用来自zoo包的na.locf()函数,以将最后观测值往前填充替换你的NA值。以下是从帮助页面开始的用法示例:
library(zoo)

az <- zoo(1:6)

bz <- zoo(c(2,NA,1,4,5,2))

na.locf(bz)
1 2 3 4 5 6 
2 2 1 4 5 2 

na.locf(bz, fromLast = TRUE)
1 2 3 4 5 6 
2 1 1 4 5 2 

cz <- zoo(c(NA,9,3,2,3,2))

na.locf(cz)
2 3 4 5 6 
9 3 2 3 2 

2
还要注意,zoo中的na.locf函数可以处理普通向量以及zoo对象。它的na.rm参数在某些应用中非常有用。 - G. Grothendieck
12
使用na.locf(cz, na.rm=FALSE)可以保留前导的NA值。 - BallpointBen
1
@BallpointBen的评论很重要,应该包含在答案中。谢谢! - Ben

76

抱歉挖起了一个旧问题。我在火车上找不到做这项工作的函数,所以我自己写了一个。

我很自豪地发现它稍微快了一点。
尽管它不是很灵活。

但它与 ave 很搭配,这正是我需要的。

repeat.before = function(x) {   # repeats the last non NA value. Keeps leading NA
    ind = which(!is.na(x))      # get positions of nonmissing values
    if(is.na(x[1]))             # if it begins with a missing, add the 
          ind = c(1,ind)        # first position to the indices
    rep(x[ind], times = diff(   # repeat the values at these indices
       c(ind, length(x) + 1) )) # diffing the indices + length yields how often 
}                               # they need to be repeated

x = c(NA,NA,'a',NA,NA,NA,NA,NA,NA,NA,NA,'b','c','d',NA,NA,NA,NA,NA,'e')  
xx = rep(x, 1000000)  
system.time({ yzoo = na.locf(xx,na.rm=F)})  
## user  system elapsed   
## 2.754   0.667   3.406   
system.time({ yrep = repeat.before(xx)})  
## user  system elapsed   
## 0.597   0.199   0.793   

编辑

由于这篇回答成为了我最受欢迎的回答,我经常被提醒自己没有使用我的函数,因为我经常需要 zoo 的 maxgap 参数。因为当我使用 dplyr + 日期时,zoo 在边缘情况下存在一些奇怪的问题,我无法调试,所以今天回到这里改进我的旧函数。

我对我的改进函数和所有其他条目进行了基准测试。就基本功能而言,tidyr::fill 是最快的,同时也不会失败。@BrandonBertelsen 的 Rcpp 条目仍然更快,但是它在输入类型上不够灵活(他由于误解 all.equal 而错误地测试了边缘情况)。

如果您需要 maxgap,则我下面的函数比 zoo 更快(并且不会出现与日期相关的奇怪问题)。

我发布了我的测试文档

新函数

repeat_last = function(x, forward = TRUE, maxgap = Inf, na.rm = FALSE) {
    if (!forward) x = rev(x)           # reverse x twice if carrying backward
    ind = which(!is.na(x))             # get positions of nonmissing values
    if (is.na(x[1]) && !na.rm)         # if it begins with NA
        ind = c(1,ind)                 # add first pos
    rep_times = diff(                  # diffing the indices + length yields how often
        c(ind, length(x) + 1) )          # they need to be repeated
    if (maxgap < Inf) {
        exceed = rep_times - 1 > maxgap  # exceeding maxgap
        if (any(exceed)) {               # any exceed?
            ind = sort(c(ind[exceed] + 1, ind))      # add NA in gaps
            rep_times = diff(c(ind, length(x) + 1) ) # diff again
        }
    }
    x = rep(x[ind], times = rep_times) # repeat the values at these indices
    if (!forward) x = rev(x)           # second reversion
    x
}

我也把这个函数放在我的formr包中(仅限于Github)。


47

使用 data.table 的解决方案:

dt <- data.table(y = c(NA, 2, 2, NA, NA, 3, NA, 4, NA, NA))
dt[, y_forward_fill := y[1], .(cumsum(!is.na(y)))]
dt
     y y_forward_fill
 1: NA             NA
 2:  2              2
 3:  2              2
 4: NA              2
 5: NA              2
 6:  3              3
 7: NA              3
 8:  4              4
 9: NA              4
10: NA              4

这种方法也可以使用向前填充零来实现:

dt <- data.table(y = c(0, 2, -2, 0, 0, 3, 0, -4, 0, 0))
dt[, y_forward_fill := y[1], .(cumsum(y != 0))]
dt
     y y_forward_fill
 1:  0              0
 2:  2              2
 3: -2             -2
 4:  0             -2
 5:  0             -2
 6:  3              3
 7:  0              3
 8: -4             -4
 9:  0             -4
10:  0             -4

这种方法在处理大规模数据和按组执行向前填充时非常有用,使用data.table易如反掌。只需在cumsum逻辑之前将组添加到by子句即可。

dt <- data.table(group = sample(c('a', 'b'), 20, replace = TRUE), y = sample(c(1:4, rep(NA, 4)), 20 , replace = TRUE))
dt <- dt[order(group)]
dt[, y_forward_fill := y[1], .(group, cumsum(!is.na(y)))]
dt
    group  y y_forward_fill
 1:     a NA             NA
 2:     a NA             NA
 3:     a NA             NA
 4:     a  2              2
 5:     a NA              2
 6:     a  1              1
 7:     a NA              1
 8:     a  3              3
 9:     a NA              3
10:     a NA              3
11:     a  4              4
12:     a NA              4
13:     a  1              1
14:     a  4              4
15:     a NA              4
16:     a  3              3
17:     b  4              4
18:     b NA              4
19:     b NA              4
20:     b  2              2

1
我熟悉tidyverse,但是对于data.table还很陌生 - 可以问一下这段代码的作用吗?dt[, y_forward_fill := y[1], .(cumsum(!is.na(y)))]具体来说,y[1]和.(cumsum(!is.na(y)))为什么可以填充缺失值? - Desmond
嗨@TonyDiFranco,如果意图是向后填充,你会建议某人如何实现这个? - Jantje Houten
@JantjeHouten 最简单但不是最有效的方法是反转数据表的排序顺序,执行前向填充,然后再次反转回原始顺序。 - Tony DiFranco

36

tidyr 包(tidyverse 套件的一部分)有一个简单的方法来做到这一点:

y = c(NA, 2, 2, NA, NA, 3, NA, 4, NA, NA)

# first, transform it into a data.frame

df = as.data.frame(y)
   y
1  NA
2   2
3   2
4  NA
5  NA
6   3
7  NA
8   4
9  NA
10 NA

library(tidyr)
fill(df, y, .direction = 'down')
    y
1  NA
2   2
3   2
4   2
5   2
6   3
7   3
8   4
9   4
10  4

1
这个函数的缺点是,首先需要创建原子向量as.data.frame(),而且输出也是一个data.frame而不是原子向量。 - AnilGoyal
1
@AnilGoyal 这对我的情况来说是一个好消息。 - Julien

35

你可以使用 data.table 函数 nafill,该函数在 data.table >= 1.12.3 中可用。

library(data.table)
nafill(y, type = "locf")
# [1] NA  2  2  2  2  3  3  4  4  4

如果您的向量是 data.table 中的一列,您还可以使用 setnafill 来进行引用更新:
d <- data.table(x = 1:10, y)
setnafill(d, type = "locf", cols = "y")
d
#      x  y
#  1:  1 NA
#  2:  2  2
#  3:  3  2
#  4:  4  2
#  5:  5  2
#  6:  6  3
#  7:  7  3
#  8:  8  4
#  9:  9  4
# 10: 10  4

如果您在多列中有NA...

d <- data.table(x = c(1, NA, 2), y = c(2, 3, NA), z = c(4, NA, 5))
#     x  y  z
# 1:  1  2  4
# 2: NA  3 NA
# 3:  2 NA  5

...你可以通过引用一次性填充它们:

setnafill(d, type = "locf")
d
#    x y z
# 1: 1 2 4
# 2: 1 3 4
# 3: 2 3 5

请注意:

目前仅支持doubleinteger数据类型[data.table 1.12.6]。

很可能很快就会扩展功能;请参见开放问题nafill,setnafill用于字符,因子和其他类型,在那里您还可以找到临时解决方法


24

我也要加入:

library(Rcpp)
cppFunction('IntegerVector na_locf(IntegerVector x) {
  int n = x.size();

  for(int i = 0; i<n; i++) {
    if((i > 0) && (x[i] == NA_INTEGER) & (x[i-1] != NA_INTEGER)) {
      x[i] = x[i-1];
    }
  }
  return x;
}')

搭建一个基本的示例和基准测试:

x <- sample(c(1,2,3,4,NA))

bench_em <- function(x,count = 10) {
  x <- sample(x,count,replace = TRUE)
  print(microbenchmark(
    na_locf(x),
    replace_na_with_last(x),
    na.lomf(x),
    na.locf(x),
    repeat.before(x)
  ), order = "mean", digits = 1)
}

运行一些基准测试:

bench_em(x,1e6)

Unit: microseconds
                    expr   min    lq  mean median    uq   max neval
              na_locf(x)   697   798   821    814   821 1e+03   100
              na.lomf(x)  3511  4137  5002   4214  4330 1e+04   100
 replace_na_with_last(x)  4482  5224  6473   5342  5801 2e+04   100
        repeat.before(x)  4793  5044  6622   5097  5520 1e+04   100
              na.locf(x) 12017 12658 17076  13545 19193 2e+05   100

以防万一:

all.equal(
     na_locf(x),
     replace_na_with_last(x),
     na.lomf(x),
     na.locf(x),
     repeat.before(x)
)
[1] TRUE

更新

对于数字向量,该函数略有不同:

NumericVector na_locf_numeric(NumericVector x) {
  int n = x.size();
  LogicalVector ina = is_na(x);

  for(int i = 1; i<n; i++) {
    if((ina[i] == TRUE) & (ina[i-1] != TRUE)) {
      x[i] = x[i-1];
    }
  }
  return x;
}

23

在处理大量数据时,为了更高效地工作,我们可以使用data.table包。

require(data.table)
replaceNaWithLatest <- function(
  dfIn,
  nameColNa = names(dfIn)[1]
){
  dtTest <- data.table(dfIn)
  setnames(dtTest, nameColNa, "colNa")
  dtTest[, segment := cumsum(!is.na(colNa))]
  dtTest[, colNa := colNa[1], by = "segment"]
  dtTest[, segment := NULL]
  setnames(dtTest, "colNa", nameColNa)
  return(dtTest)
}

2
可以添加lapply,以便直接将其应用于多个NA列:replaceNaWithLatest <- function( dfIn, nameColsNa = names(dfIn)[1] ){ dtTest <- data.table(dfIn) invisible(lapply(nameColsNa, function(nameColNa){ setnames(dtTest, nameColNa, "colNa") dtTest[, segment := cumsum(!is.na(colNa))] dtTest[, colNa := colNa[1], by = "segment"] dtTest[, segment := NULL] setnames(dtTest, "colNa", nameColNa) })) return(dtTest) } - xclotet
起初我对这个解决方案感到兴奋,但实际上它根本没有做同样的事情。问题是关于用另一个数据集填充一个数据集。而这个答案只是插补。 - Hack-R

20

这对我起作用:

  replace_na_with_last<-function(x,a=!is.na(x)){
     x[which(a)[c(1,1:sum(a))][cumsum(a)+1]]
  }


> replace_na_with_last(c(1,NA,NA,NA,3,4,5,NA,5,5,5,NA,NA,NA))

[1] 1 1 1 1 3 4 5 5 5 5 5 5 5 5

> replace_na_with_last(c(NA,"aa",NA,"ccc",NA))

[1] "aa"  "aa"  "aa"  "ccc" "ccc"

速度也很合理:

> system.time(replace_na_with_last(sample(c(1,2,3,NA),1e6,replace=TRUE)))


 user  system elapsed 

 0.072   0.000   0.071 

2
当存在前导NA时,此函数不会按预期执行。replace_na_with_last(c(NA,1:4,NA))(即它们将被填充以下值)。这也是imputeTS::na.locf(x, na.remaining = "rev")的默认行为。 - Ruben
1
最好为这种情况添加一个默认值,稍微不同的方法:replace_na_with_last<-function(x,p=is.na,d=0)c(d,x)[cummax(seq_along(x)*(!p(x)))+1] - Nick Nassuphis
@NickNassuphis的回答简短、精炼,不依赖于任何包,并且与dplyr管道很好地配合使用! - Kim

15

在前面带有NA的情况下,处理LOCF的一个小问题是,当主要项不缺失时,我找到了一种非常可读(且向量化)的方法:

na.omit(y)[cumsum(!is.na(y))]

稍微不太容易理解的修改可以普遍适用:

c(NA, na.omit(y))[cumsum(!is.na(y))+1]

可以得到所需输出:

c(NA, 2, 2, 2, 2, 3, 3, 4, 4, 4)


14

尝试使用此函数。它不需要ZOO包:

# last observation moved forward
# replaces all NA values with last non-NA values
na.lomf <- function(x) {

    na.lomf.0 <- function(x) {
        non.na.idx <- which(!is.na(x))
        if (is.na(x[1L])) {
            non.na.idx <- c(1L, non.na.idx)
        }
        rep.int(x[non.na.idx], diff(c(non.na.idx, length(x) + 1L)))
    }

    dim.len <- length(dim(x))

    if (dim.len == 0L) {
        na.lomf.0(x)
    } else {
        apply(x, dim.len, na.lomf.0)
    }
}

示例:

> # vector
> na.lomf(c(1, NA,2, NA, NA))
[1] 1 1 2 2 2
> 
> # matrix
> na.lomf(matrix(c(1, NA, NA, 2, NA, NA), ncol = 2))
     [,1] [,2]
[1,]    1    2
[2,]    1    2
[3,]    1    2

要进行改进,您可以添加以下代码:if (!anyNA(x)) return(x) - Artem Klevtsov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接