Irakli Irakli - 1 year ago 81
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, | myvec!='test', 'good')

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

Answer Source

One option is using diff with cumsum

c('good', 'test', 'bad')[cumsum(c(TRUE, abs(diff(myvec == "test" & !]
#[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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download