r - str_detect 还在过滤器中找到 NA

标签 r filter stringr

我想过滤掉列中包含字符串的行。我正在使用 tidyverse 解决方案。我遇到的问题是 str_detect 似乎也在寻找 NA 结果,因此这些也被我的过滤器删除了:

df1 = data.frame(x1 = c("PI", NA, "Yes", "text"),
                 x2 = as.character(c(NA, 1, NA,"text")),
                 x3 = c("foo", "bar","foo", "bar"))

> df1
    x1   x2  x3
1   PI <NA> foo
2 <NA>    1 bar
3  Yes <NA> foo
4 text text bar

#remove rows which have "PI" in column `x1`:

df2 = df1%>%
  filter(!str_detect(x1, "(?i)pi"))

> df2
    x1   x2  x3
1  Yes <NA> foo
2 text text bar

如何防止 str_detect 发现 NA

最佳答案

使用 is.na| 添加条件。 NA 问题只是因为对于 NA 元素,str_detect 返回 NA,它会被 自动删除>过滤器

library(dplyr)
library(stringr)
df1 %>%
    filter(is.na(x1) |
       str_detect(x1, regex("pi", ignore_case = TRUE), negate = TRUE))

-输出

   x1   x2  x3
1 <NA>    1 bar
2  Yes <NA> foo
3 text text bar

即检查 str_detect

的输出
with(df1, str_detect(x1, regex("pi", ignore_case = TRUE), negate = TRUE))
[1] FALSE    NA  TRUE  TRUE

NA 保持不变,除非我们让它为真

 with(df1, str_detect(x1, regex("pi", ignore_case = TRUE), negate = TRUE)|is.na(x1))
[1] FALSE  TRUE  TRUE  TRUE

或者另一种选择是将 coalesceTRUE 以便 str_detect 中的所有 NA 元素都将更改为TRUE

df1 %>% 
   filter(coalesce(str_detect(x1, regex("pi", ignore_case = TRUE), 
       negate = TRUE), TRUE))
    x1   x2  x3
1 <NA>    1 bar
2  Yes <NA> foo
3 text text bar

关于r - str_detect 还在过滤器中找到 NA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68838895/

相关文章:

javascript - 日期范围过滤器不起作用

date - 过滤范围日期elasticsearch

javascript - 内部有 promise 的 Angular 自定义过滤器

r - 在 R 中解析该结构化文本文件

r - 使用 R Markdown 文档作为函数源

css - 控制数据表输出中的行条纹颜色

R:如何删除data.table中的列?

r - 计算 R 中的二维样条曲线

r - 提取第一个和第二个空格之间的字符串

r - 如何使用正则表达式替换 '\U'?