R:在滿足條件之前和之后替換向量中的值

[英]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:

如何在'test'之前替換向量中的所有元素,例如'good',之后用'bad'替換?結果應該是:

[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"

1 个解决方案

#1


2  

One option is using diff with cumsum

一種選擇是使用帶有cumsum的diff

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

或者如評論中提到的@nicola,可以使用帶匹配的符號

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

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2016/11/02/72a1be1c5dfd677f073dfc96fa3e7fda.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com