R:在满足条件之前和之后替换向量中的值

时间:2016-11-02 16:04:52

标签: r vector replace conditional

考虑缺少值的向量:

dp.dta.DTypeArray[0] = 15;

如何在'test'之前用'good'替换vector中的所有元素,然后用'bad'替换它?结果应该是:

myvec <- c('C', NA, 'test', NA, 'D')

[1] "C"   NA   "test"  NA   "D"   

我的尝试成功只能用'好'替换所有东西,这不太好:

[1] "good" "good" "test" "bad"  "bad" 

1 个答案:

答案 0 :(得分:2)

一种选择是将diffcumsum

一起使用
c('good', 'test', 'bad')[cumsum(c(TRUE, abs(diff(myvec == "test" & !is.na(myvec)))==1))]
#[1] "good" "good" "test" "bad"  "bad" 

或使用which

i1 <- which(myvec=='test')
myvec[1:(i1-1)] <- 'good'
myvec[(i1+1):length(myvec)] <- 'bad'

或者在评论中提到@nicola时,sign可以使用match

c("good","test","bad")[sign(seq_along(myvec)-match("test",my‌​vec))+2]