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

这是一种方法

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 回答