开发者

excluding FALSE elements from a character vector by using logical vector

I manage to do the following:

stuf开发者_Python百科f <- c("banana_fruit","apple_fruit","coin","key","crap")
fruits <- stuff[stuff %in% grep("fruit",stuff,value=TRUE)]

but I can't get select the-not-so-healthy stuff with the usual thoughts and ideas like

no_fruit <- stuff[stuff  %not in% grep("fruit",stuff,value=TRUE)]
#or
no_fruit <- stuff[-c(stuff  %in% grep("fruit",stuff,value=TRUE))]

don't work. The latter just ignores the "-"


> stuff[grep("fruit",stuff)]
[1] "banana_fruit" "apple_fruit" 
> stuff[-grep("fruit",stuff)]
[1] "coin" "key"  "crap"

You can only use negative subscripts with numeric/integer vectors, not logical because:

> -TRUE
[1] -1

If you want to negate a logical vector, use !:

> !TRUE
[1] FALSE


As Joshua mentioned: you can't use - to negate your logical index; use ! instead.

stuff[!(stuff %in% grep("fruit",stuff,value=TRUE))]

See also the stringr package for this kind of thing.

stuff[!str_detect(stuff, "fruit")]


There is also a parameter called 'invert' in grep that does essentially what you're looking for:

> stuff <- c("banana_fruit","apple_fruit","coin","key","crap")
> fruits <- stuff[stuff %in% grep("fruit",stuff,value=TRUE)]
> fruits
[1] "banana_fruit" "apple_fruit" 
> grep("fruit", stuff, value = T)
[1] "banana_fruit" "apple_fruit" 
> grep("fruit", stuff, value = T, invert = T)
[1] "coin" "key"  "crap"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜