【问题标题】:Filter the values in a variable in a dataframe which match a regular expression using grep in R使用 R 中的 grep 过滤数据框中与正则表达式匹配的变量中的值
【发布时间】:2019-06-24 02:18:54
【问题描述】:

我有这样的数据

data <- data.frame(
  ID_num = c("BGR9876", "BNG3421", "GTH4567", "YOP9824", "Child 1", "2JAZZ", "TYH7654"),
  date_created = "19/07/1983"
)

我想过滤数据框,以便只保留 ID_num 遵循模式 ABC1234 的行。我是在 grep 中使用正则表达式的新手,我弄错了。这就是我正在尝试的

data_clean <- data %>%
  filter(grep("[A-Z]{3}[1:9]{4}", ID_num))

这给了我错误Error in filter_impl(.data, quo) : Argument 2 filter condition does not evaluate to a logical vector

这是我想要的输出

data_clean <- data.frame(
  ID_num = c("BGR9876", "BNG3421", "GTH4567", "YOP9824", "TYH7654"),
  date_created = "19/07/1983"
)

谢谢

【问题讨论】:

    标签: r regex dplyr


    【解决方案1】:

    我们可以在模式中使用grepl

    data[grepl("[A-Z]{3}\\d{4}", data$ID_num), ]
    
    #   ID_num date_created
    #1 BGR9876   19/07/1983
    #2 BNG3421   19/07/1983
    #3 GTH4567   19/07/1983
    #4 YOP9824   19/07/1983
    #7 TYH7654   19/07/1983
    

    或在filter

    library(dplyr)
    data %>% filter(grepl("[A-Z]{3}\\d{4}", ID_num))
    

    【讨论】:

      【解决方案2】:

      1:9 应为 1-9grepl^ 指定字符串的开头,$ 指定字符串的结尾

      library(dplyr)
      data %>%
         filter(grepl("^[A-Z]{3}[1-9]{4}$", ID_num))
      #   ID_num date_created
      #1 BGR9876   19/07/1983
      #2 BNG3421   19/07/1983
      #3 GTH4567   19/07/1983
      #4 YOP9824   19/07/1983
      #5 TYH7654   19/07/1983
      

      filter 需要一个逻辑向量,grep 返回数字索引,而grepl 返回逻辑向量


      或者如果我们想使用grep,请使用slice,它需要数字索引

      data %>%
         slice(grep("^[A-Z]{3}[1-9]{4}$", ID_num))
      

      tidyverse 中的类似选项是使用 str_detect

      library(stringr)
      data %>%
          filter(str_detect(ID_num, "^[A-Z]{3}[1-9]{4}$"))
      

      base R,我们可以做

      subset(data, grepl("^[A-Z]{3}[1-9]{4}$", ID_num))
      

      Extract

      data[grepl("^[A-Z]{3}[1-9]{4}$", data$ID_num),]
      

      注意这里会专门找3个大写字母后跟4个数字的模式,不匹配

      grepl("[A-Z]{3}[1-9]{4}", "ABGR9876923")
      #[1] TRUE
      
      grepl("^[A-Z]{3}[1-9]{4}$", "ABGR9876923")
      #[1] FALSE
      

      【讨论】:

        猜你喜欢
        • 2015-07-02
        • 1970-01-01
        • 1970-01-01
        • 2020-04-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-11
        • 1970-01-01
        相关资源
        最近更新 更多