2
foo <- c("a","a",NA,"b","a","a","b","b")

前の要素が NA の場合、「b」を何かに置き換える方法は?

foo[foo=="b" & "previous-element"==NA] <- "whatever"

したがって、期待される出力は次のようになります。

result <- c("a","a",NA,"whatever","a","a","b","b")

そのため、NA が前に付いた "b" (実際のデータの多く) のみが変更されます。

助けてくれてありがとう!

4

3 に答える 3

7

簡単な解決策:

foo[-1][foo[-1] == "b" & is.na(head(foo, -1))] <- "whatever"

アップデート:

パッケージrollapplyからのソリューション:zoo

library(zoo)
foo[-1][rollapply(foo, 2, identical, c(NA, "b"))] <- "whatever"
于 2012-11-07T20:57:27.270 に答える
2

ここに1つの方法があります

foo <- c("a","a",NA,"b","a","a","b","b")

nas <- which(is.na(foo))  ## which are NA
bs <- which(foo == "b")   ## which are "b"

## the match() finds the index in nas that matches the one in bs - 1
foo[bs[match(nas, bs - 1)]] <- "whatever"
foo

結果は

> foo
[1] "a"        "a"        NA         "whatever" "a"       
[6] "a"        "b"        "b"

使いやすくするために、これを関数にラップします。

whatever <- function(x) {
  nas <- which(is.na(x))
  bs <- which(x == "b")
  x[bs[match(nas, bs - 1)]] <- "whatever"
  x
}

を与える

> foo <- c("a","a",NA,"b","a","a","b","b")
> whatever(foo)
[1] "a"        "a"        NA         "whatever" "a"       
[6] "a"        "b"        "b"
于 2012-11-07T20:51:51.923 に答える
2

embed楽しみのためだけに使用する完全に複雑なソリューション:

foo[which(
          apply(
                embed(foo,2),
                1,
                function(x) x[1]=="b" & is.na(x[2])
               )
         ) + 1
    ] <- "whatever"

> foo
[1] "a" "a" NA "whatever" "a" "a" "b" "b"      
于 2012-11-07T21:09:40.450 に答える