Irakli Irakli - 1 month ago 6
R Question

R: replace values in a vector before and after a condition is met

Consider a vector with missing values:

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

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


How to replace all the elements in the vector before 'test' with, say, 'good' and after it with 'bad'? The outcome should be:

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


My attempt below succeeds only in replacing everything with 'good', which is not so good:

replace(myvec, is.na(myvec) | myvec!='test', 'good')

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

Answer

One option is using diff with cumsum

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

Or use which

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

Or as @nicola mentioned in the comments, sign with match can be used

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