ここに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"