[英]Why in R are grep & !grep not logically consistent when grepl and !grepl ARE logically consistent?
R functions grep
and !grep
(NOT grep) are not logically consistent; R函数
grep
和!grep
(非grep)在逻辑上不一致; unlike grepl
and !grepl
(NOT grepl) which ARE logically consistent. 与
grepl
和!grepl
(NOT grepl)在逻辑上是一致的。
grepl
returns a logical vector equal in length to the number of items being searched. grepl
返回一个逻辑向量,该向量的长度等于要搜索的项目数。 For example, if the target is found in items 2 and 3 of a 5-item vector the following is returned: 例如,如果在5项向量的项目2和3中找到目标,则返回以下内容:
FALSE TRUE TRUE FALSE FALSE
If grepl
is replaced by !grepl
, then the "opposite" logical result is returned: 如果将
grepl
替换为!grepl
,则返回“相反”的逻辑结果:
TRUE FALSE FALSE TRUE TRUE
grep
, on other hand returns a vector of the 2 positions of the found items: 2 3
grep
,另一方面,返回找到的项目的2个位置的向量: 2 3
What does !grep
return in the same scenario? !grep
在相同的情况下返回什么? Logically it should return 1 4 5
, instead it returns FALSE FALSE
. 从逻辑上讲,它应该返回
1 4 5
,而不是返回FALSE FALSE
。 How can that be a logically consistent returned value? 这怎么能成为逻辑上一致的返回值? Can anyone explain?
谁能解释?
You are looking for the invert
argument to grep()
. 您正在寻找
grep()
的invert
参数。
From help(grep)
, under Arguments : 从
help(grep)
Arguments下:
invert - logical.
反转 -逻辑。 If
TRUE
return indices or values for elements that do not match.如果为
TRUE
返回不匹配元素的索引或值。
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. grep(value = FALSE)-返回产生匹配项的x元素索引的向量。
grepl returns a logical vector (match or not for each element of x). grepl返回逻辑向量(是否匹配x的每个元素)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.