177

data.frame(または)では、data.tableNAを最も近い以前の非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

この操作を多くの(合計〜1 Tb)小さいサイズdata.frameのs(〜30-50 Mb)に対して繰り返す必要があります。ここで、行は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

...これはうまくいくようです。しかし、男、それは醜いですか!助言がありますか?

4

19 に答える 19

184

おそらく、 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 
于 2011-10-12T05:32:08.390 に答える
70

古い質問を掘り下げてすみません。電車の中でこの仕事をする機能を探すことができなかったので、自分で書きました。

私はそれが少し速いことを知って誇りに思いました。
ただし、柔軟性は低くなります。

しかし、それは私が必要としていたものとうまく機能し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   

編集

maxgapこれが私の最も賛成の答えになったので、私は動物園の議論をしばしば必要とするので、私は自分の関数を使用しないことをしばしば思い出しました。デバッグできなかったdplyr+日付を使用すると、エッジケースで動物園に奇妙な問題が発生するため、今日、古い関数を改善するためにこれに戻りました。

改善された機能と他のすべてのエントリをここでベンチマークしました。機能の基本セットについては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
}

関数をformerパッケージにも入れました(Githubのみ)。

于 2012-12-10T22:45:39.627 に答える
37

解決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です。ロジックbyの前の句にグループを追加するだけです。cumsum

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
于 2017-08-09T16:02:39.337 に答える
27

から利用できる関数を使用できdata.tableます。nafilldata.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

ご了承ください:

現在、 doubleおよびintegerデータ型のみがdata.table 1.12.6サポートされています[]。

機能は間もなく拡張される可能性があります。未解決の問題のnafill、文字、因子、およびその他のタイプのsetnafillを参照してください。ここには、一時的な回避策もあります。

于 2019-04-19T16:40:00.137 に答える
22

ビッグデータを処理する場合、効率を上げるために、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)
}
于 2015-03-03T22:07:24.150 に答える
22

私の帽子を投げる:

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;
}
于 2016-09-03T08:38:38.987 に答える
19

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
于 2020-05-07T10:36:24.417 に答える
18

これは私のために働いています:

  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 
于 2016-05-25T21:02:27.337 に答える
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)

于 2018-01-29T23:00:56.927 に答える
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
于 2014-05-11T12:01:31.830 に答える
6

na.locfNA最後の観測の繰り越し)機能を提供するパッケージがたくさんあります。

  • xts-xts::na.locf
  • zoo-zoo::na.locf
  • imputeTS- imputeTS::na.locf
  • spacetime-spacetime::na.locf

また、この関数の名前が異なる他のパッケージもあります。

于 2016-11-11T05:51:43.130 に答える
3

BrandonBertelsenのRcppの貢献をフォローアップします。私にとって、NumericVectorバージョンは機能しませんでした:それは最初のNAを置き換えるだけでした。これはina、関数の開始時にベクトルが1回だけ評価されるためです。

代わりに、IntegerVector関数の場合とまったく同じアプローチを取ることができます。以下は私のために働いた:

library(Rcpp)
cppFunction('NumericVector na_locf_numeric(NumericVector x) {
  R_xlen_t n = x.size();
  for(R_xlen_t i = 0; i<n; i++) {
    if(i > 0 && !R_finite(x[i]) && R_finite(x[i-1])) {
      x[i] = x[i-1];
    }
  }
  return x;
}')

CharacterVectorバージョンが必要な場合は、同じ基本的なアプローチも機能します。

cppFunction('CharacterVector na_locf_character(CharacterVector x) {
  R_xlen_t n = x.size();
  for(R_xlen_t i = 0; i<n; i++) {
    if(i > 0 && x[i] == NA_STRING && x[i-1] != NA_STRING) {
      x[i] = x[i-1];
    }
  }
  return x;
}')
于 2017-02-17T22:08:32.540 に答える
3

これが@AdamOのソリューションの変更です。これはna.omit関数をバイパスするため、より高速に実行されます。NAこれにより、ベクトルの値が上書きされますy(先頭のsを除くNA)。

   z  <- !is.na(y)                  # indicates the positions of y whose values we do not want to overwrite
   z  <- z | !cumsum(z)             # for leading NA's in y, z will be TRUE, otherwise it will be FALSE where y has a NA and TRUE where y does not have a NA
   y  <- y[z][cumsum(z)]
于 2018-03-22T00:16:02.687 に答える
3

runnerrcranパッケージを使用する次のソリューションを追加したいと思います。

library(runner)
y <- c(NA, 2, 2, NA, NA, 3, NA, 4, NA, NA)
fill_run(y, FALSE)
 [1] NA  2  2  2  2  3  3  4  4  4

パッケージ全体が最適化されており、その大部分はcppで記述されています。したがって、優れた効率を提供します。

于 2020-09-23T21:45:40.770 に答える
1

私は個人的にこの機能を使用しています。どれくらい速いのか遅いのかわかりません。しかし、ライブラリを使用せずにその仕事をします。

replace_na_with_previous<-function (vector) {
        if (is.na(vector[1])) 
            vector[1] <- na.omit(vector)[1]
        for (i in 1:length(vector)) {
            if ((i - 1) > 0) {
                if (is.na(vector[i])) 
                    vector[i] <- vector[i - 1]
            }
        }
        return(vector)
    }

この関数をデータフレームに適用する場合、データフレームがdfと呼ばれる場合は、単純に

df[]<-lapply(df,replace_na_with_previous)
于 2020-02-21T11:36:18.083 に答える
0

私は以下を試しました:

nullIdx <- as.array(which(is.na(masterData$RequiredColumn)))
masterData$RequiredColumn[nullIdx] = masterData$RequiredColumn[nullIdx-1]

nullIdxは、masterData$RequiredColumnにNull/NA値がある場合は常にidx番号を取得します。次の行では、対応するIdx-1値、つまり各NULL/NAの前の最後の適切な値に置き換えます。

于 2016-10-27T16:03:10.203 に答える
0

これは私にとってはうまくいきましたが、他の提案よりも効率的かどうかはわかりません。

rollForward <- function(x){
  curr <- 0
  for (i in 1:length(x)){
    if (is.na(x[i])){
      x[i] <- curr
    }
    else{
      curr <- x[i]
    }
  }
  return(x)
}
于 2017-01-13T19:16:30.413 に答える
0
fill.NAs <- function(x) {is_na<-is.na(x); x[Reduce(function(i,j) if (is_na[j]) i else j, seq_len(length(x)), accumulate=T)]}

fill.NAs(c(NA, 2, 2, NA, NA, 3, NA, 4, NA, NA))

[1] NA  2  2  2  2  3  3  4  4  4

Reduceは、同様のタスクに役立つ可能性のある優れた関数型プログラミングの概念です。repeat.before残念ながら、Rでは上記の回答よりも約70倍遅くなります。

于 2019-04-24T13:03:41.527 に答える
0

これは、尋ねられた質問と同様の問題を抱えている他の人に役立つ可能性があるため、ここに投稿します。

パッケージを使用する最新のtidyverseソリューションを組み合わせて、新しい列を作成できますvctrsmutate

library(dplyr)
library(magrittr)
library(vctrs)

as.data.frame(y) %>%
  mutate(y_filled = vec_fill_missing(y, direction = c("down")) )

戻り値

   y  y_filled
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

「充填方向」を次のように変更すると、次のようになり'up'ます。

    y  y_filled
1  NA        2
2   2        2
3   2        2
4  NA        3
5  NA        3
6   3        3
7  NA        4
8   4        4
9  NA       NA
10 NA       NA

また試してみたいかもしれません"downup""updown"

このソリューションはまだ実験的なライフサイクルであるため、構文が変更される可能性があることに注意してください。

于 2021-11-23T14:02:51.793 に答える