[英]AND grepl operation in R
Suppose I have the following character 假设我有以下特征
c <- "1 NA NA 4 5 6 NA NA 9 10 NA NA 13 14 15 16 17 18 19 20 NA NA 23 NA NA NA NA"
How can I grepl it to test it contains 1 and 5 and 6? 我怎样才能测试它包含1和5和6? Without getting 15, 16, etc. as false positive? 没有得到15,16等假阳性?
You can use word boundary \\\\b
around 1,5,6
: 您可以在1,5,6
左右使用字边界\\\\b
:
grepl("\\b[156]\\b", c)
# [1] TRUE
If you want to check if all of the 1,5,6
are contained in the string, you can vectorize grepl
on the pattern position: 如果要检查字符串中是否包含所有1,5,6
,可以在模式位置上向量化grepl
:
all(Vectorize(grepl)(paste("\\b", c(1,5,6), "\\b", sep = ""), c))
# [1] TRUE
When we remove 1
from the string: 当我们从字符串中删除1
:
c <- "NA NA 4 5 6 NA NA 9 10 NA NA 13 14 15 16 17 18 19 20 NA NA 23 NA NA NA NA"
grepl("\\b[156]\\b", c) # this is or condition, will still give true
# [1] TRUE
all(Vectorize(grepl)(paste("\\b", c(1,5,6), "\\b", sep = ""), c)) # This gives FALSE since
# pattern \\b1\\b is not there
# [1] FALSE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.