我设法做到以下几点:
stuff <- c("banana_fruit","apple_fruit","coin","key","crap")
fruits <- stuff[stuff %in% grep("fruit",stuff,value=TRUE)]
但我无法通过像
这样的常见想法和想法来选择那些不那么健康的东西no_fruit <- stuff[stuff %not in% grep("fruit",stuff,value=TRUE)]
#or
no_fruit <- stuff[-c(stuff %in% grep("fruit",stuff,value=TRUE))]
不行。后者只是忽略了“ - ”
答案 0 :(得分:4)
> stuff[grep("fruit",stuff)]
[1] "banana_fruit" "apple_fruit"
> stuff[-grep("fruit",stuff)]
[1] "coin" "key" "crap"
您只能使用带有数字/整数向量的负下标,而不是逻辑,因为:
> -TRUE
[1] -1
如果要取消逻辑向量,请使用!
:
> !TRUE
[1] FALSE
答案 1 :(得分:2)
正如约书亚所说:你不能用-
否定你的逻辑指数;请改用!
。
stuff[!(stuff %in% grep("fruit",stuff,value=TRUE))]
另请参阅此stringr
包。
stuff[!str_detect(stuff, "fruit")]
答案 2 :(得分:1)
在grep中还有一个名为'invert'的参数,它基本上可以满足您的需求:
> 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"