grepl逐个元素地处理两个向量
grepl on two vectors element by element
我想对两个向量应用 grepl
以查看第一个向量的元素是否在第二个向量的相应元素中可用。例如
grepl(c("bc","23","a2"),c("abcd","1234","zzzz"))
并且由于 bc
在 abcd
中,23
在 1234
中并且 a2
不在 zzzz
中,我会喜欢TRUE TRUE FALSE
。但是,我得到的是:
[1] TRUE FALSE FALSE
Warning message:
In grepl(c("bc", "23", "a2"), c("abcd", "1234", "zzzz")) :
argument 'pattern' has length > 1 and only the first element will be used
试试 or 运算符
grepl(c("bc|23|a2"),c("abcd","1234","zzzz"))
我们可以在这里尝试使用 mapply
:
fun <- function(x, y) {
grepl(x, y)
}
mapply(fun, c("bc","23","a2"), c("abcd","1234","zzzz"))
bc 23 a2
TRUE TRUE FALSE
stringr
包(依赖于 stringi
)提供自然向量化的 regex
函数:
require(stringr)
str_detect(string=c("abcd","1234","zzzz"),pattern=c("bc","23","a2"))
#[1] TRUE TRUE FALSE
请注意参数顺序与 grep
不同。
我们也可以使用 purrr
:
purrr::map2(c("bc","23","a2"),c("abcd","1234","zzzz"),
function(x,y) grepl(x,y))
[[1]]
[1] TRUE
[[2]]
[1] TRUE
[[3]]
[1] FALSE
如果你想留在base
:
unlist(Map(function(x,y) grepl(x,y), my_list[[1]],my_list[[2]]))
bc 23 a2
TRUE TRUE FALSE
我想对两个向量应用 grepl
以查看第一个向量的元素是否在第二个向量的相应元素中可用。例如
grepl(c("bc","23","a2"),c("abcd","1234","zzzz"))
并且由于 bc
在 abcd
中,23
在 1234
中并且 a2
不在 zzzz
中,我会喜欢TRUE TRUE FALSE
。但是,我得到的是:
[1] TRUE FALSE FALSE
Warning message:
In grepl(c("bc", "23", "a2"), c("abcd", "1234", "zzzz")) :
argument 'pattern' has length > 1 and only the first element will be used
试试 or 运算符
grepl(c("bc|23|a2"),c("abcd","1234","zzzz"))
我们可以在这里尝试使用 mapply
:
fun <- function(x, y) {
grepl(x, y)
}
mapply(fun, c("bc","23","a2"), c("abcd","1234","zzzz"))
bc 23 a2
TRUE TRUE FALSE
stringr
包(依赖于 stringi
)提供自然向量化的 regex
函数:
require(stringr)
str_detect(string=c("abcd","1234","zzzz"),pattern=c("bc","23","a2"))
#[1] TRUE TRUE FALSE
请注意参数顺序与 grep
不同。
我们也可以使用 purrr
:
purrr::map2(c("bc","23","a2"),c("abcd","1234","zzzz"),
function(x,y) grepl(x,y))
[[1]]
[1] TRUE
[[2]]
[1] TRUE
[[3]]
[1] FALSE
如果你想留在base
:
unlist(Map(function(x,y) grepl(x,y), my_list[[1]],my_list[[2]]))
bc 23 a2
TRUE TRUE FALSE