drmariod drmariod - 3 months ago 14
R Question

forwarding the NAs when searching with grepl in R

Is there a way to search with

grepl
and not overwriting the NAs?

grepl('test', c(NA, 'test','bla',NA))
# [1] FALSE TRUE FALSE FALSE


I would love to get
NA TRUE FALSE NA
.

Answer

Using grepl, we can try the is.na to get the expected output

as.logical(NA^is.na(v1) * grepl("test", v1))
#[1]    NA  TRUE FALSE    NA

or with 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(grepl("test", v2), is.na(v2), NA)
#[1]    NA  TRUE FALSE    NA  TRUE

data

v1 <- c(NA, 'test','bla',NA)
v2 <- c(v1, "test run")
Comments