R functions grep
and !grep
(NOT grep) are not logically consistent; unlike grepl
and !grepl
(NOT grepl) which ARE logically consistent.
grepl
returns a logical vector equal in length to the number of items being searched. For example, if the target is found in items 2 and 3 of a 5-item vector the following is returned:
FALSE TRUE TRUE FALSE FALSE
If grepl
is replaced by !grepl
, then the "opposite" logical result is returned:
TRUE FALSE FALSE TRUE TRUE
grep
, on other hand returns a vector of the 2 positions of the found items: 2 3
What does !grep
return in the same scenario? Logically it should return 1 4 5
, instead it returns FALSE FALSE
. How can that be a logically consistent returned value? Can anyone explain?
You are looking for the invert
argument to grep()
.
From help(grep)
, under Arguments :
invert - logical. If
TRUE
return indices or values for elements that do not match.
Sounds like exactly what you want. Let's see an example.
x <- c("ab", "cd", "bc", "def", "abc")
grep("b", x)
# [1] 1 3 5
grep("b", x, invert=TRUE)
# [1] 2 4
grep(value = FALSE) - returns a vector of the indices of the elements of x that yielded a match.
grepl returns a logical vector (match or not for each element of x).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.