[英]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.