[英]forwarding the NAs when searching with grepl in R
Is there a way to search with grepl
and not overwriting the NAs? 有没有办法用grepl
搜索而不是覆盖NA?
grepl('test', c(NA, 'test','bla',NA))
# [1] FALSE TRUE FALSE FALSE
I would love to get NA TRUE FALSE NA
. 我很想得到NA TRUE FALSE NA
。
Alternatively, you can use str_detect(string, pattern)
from Hadley Wickham's stringr package: 或者,您可以使用Hadley Wickham的stringr包中的str_detect(string, pattern)
:
> library(stringr)
> str_detect(c(NA, 'test','bla',NA), 'test')
[1] NA TRUE FALSE NA
Note that the arguments are in reverse order compared to grepl()
. 请注意,与grepl()
相比,参数的顺序相反。
Using grepl
, we can try the is.na
to get the expected output 使用grepl
,我们可以尝试使用is.na
来获得预期的输出
as.logical(NA^is.na(v1) * grepl("test", v1))
#[1] NA TRUE FALSE NA
or with ifelse
或与ifelse
ifelse(is.na(v1), NA, grepl("test", v1))
#[1] NA TRUE FALSE NA
ifelse(is.na(v2), NA, grepl("test", v2))
#[1] NA TRUE FALSE NA TRUE
Or with replace
或者replace
replace(grepl("test", v2), is.na(v2), NA)
#[1] NA TRUE FALSE NA TRUE
v1 <- c(NA, 'test','bla',NA)
v2 <- c(v1, "test run")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.