考虑缺少值的向量:
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"
答案 0 :(得分:2)
一种选择是将diff
与cumsum
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",myvec))+2]