【问题标题】:How can I filter a DataFrame based on a specific Pattern in R?如何根据 R 中的特定模式过滤 DataFrame?
【发布时间】:2019-12-05 13:57:01
【问题描述】:

我有一个这样的数据框:

Column_A    Column_Text
  A            hello world
  A            hi world
  B            go r
  C            dplyr 

另外,我有一个列表,有字符串模式

String_Patterns = c('world', 'go')

我想保留 Column_Text 包含“String_Patterns”模式的行。

我在 stackoverflow 上找到了一些解决方案,但它们并不完全是我想要的:

> grepl("world", df$Column_Text, fixed = FALSE) 
  # This will lead to TRUE/FALSE (not a subset), and I can only add a pattern one-by-one, for example:
> grepl(c("world", "go"), df$COlumn_Text, fixed = FALSE) # is not working... 

期望的输出:

Column_A     Column_Text
   A           hello world  #contains pattern world
   A           hi world     #contains pattern world
   B           go r         #contains pattern go

非常感谢!

【问题讨论】:

    标签: r string dplyr


    【解决方案1】:

    我们可以pastesubsetting创建模式

    subset(df, grepl(paste(String_Patterns, collapse= "|"), Column_Text))
    

    【讨论】:

    • 谢谢@akrun。但是,我认为您错过了结尾“)”。添加时,我收到错误消息:“grepl 中的错误.....参数“x”丢失,没有默认值”。有任何想法吗?提前致谢。
    【解决方案2】:

    tidyverse 等效于 akruns 答案将使用 filter 代替 subsetstr_detect 代替 greplstr_c 代替 paste

    library(dplyr)
    library(stringr)
    
    data %>% 
      filter(str_detect(Column_Text, str_c(String_Patterns, collapse = "|")))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-08
      • 1970-01-01
      • 1970-01-01
      • 2017-03-10
      相关资源
      最近更新 更多