繁体   English   中英

在 R 中使用 grep 过滤数据帧中与正则表达式匹配的变量中的值

[英]Filter the values in a variable in a dataframe which match a regular expression using grep in R

我有看起来像这样的数据

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的错误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"
)

谢谢

1:9应该是1-9并且grepl^一起指定字符串的开头和$指定字符串的结尾

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

我们可以将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))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM