tags:

views:

56

answers:

2

I manage to do the following:

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

+2  A: 
> 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
Joshua Ulrich
ok, I see. I think I need the %in% syntax though in order to get logical values that would work with subset maybe. Is there a way to invert a logical vector? meaning TRUE becomes FALSE and the other way around?
ran2
@ran: Use `!` to do that, or just use `grepl` instead.
Joshua Ulrich
just curious: is there a general way to do it? I mean outside grep or subset?
ran2
But `stuff[-grep("car",stuff)]` does not do what you expect.
hadley
@hadley: it does what it's documented to do and that's what I expect. Also, I suspected it wasn't what the questioner wanted, which is why I suggested `grepl` (as you did by commenting on Richie's answer).
Joshua Ulrich
The problem is that `grep("car",stuff)` returns `integer(0)`
hadley
@hadley: I'm aware of what it returns. As I said, that's what it's documented to return. You may disagree with the design choice, but that doesn't make it a problem.
Joshua Ulrich
+2  A: 

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")]
Richie Cotton
And see `grepl`.
hadley