R: replace values in a vector before and after a condition is met <p>Consider a vector with missing values:</p> <pre><code>myvec &lt;- c('C', NA, 'test', NA, 'D') [1] "C" NA "test" NA "D" </code></pre> <p>How to replace all the elements in the vector before 'test' with, say, 'good' and after it with 'bad'? The outcome should be:</p> <pre><code>[1] "good" "good" "test" "bad" "bad" </code></pre> <p>My attempt below succeeds only in replacing everything with 'good', which is not so good:</p> <pre><code>replace(myvec, is.na(myvec) | myvec!='test', 'good') [1] "good" "good" "test" "good" "good" </code></pre>