正则表达式(RegEx)和dplyr::filter()
我有一个简单的数据框,如下所示:正则表达式(RegEx)和dplyr::filter(),regex,r,dplyr,Regex,R,Dplyr,我有一个简单的数据框,如下所示: x <- c("aa", "aa", "aa", "bb", "cc", "cc", "cc") y <- c(101, 102, 113, 201, 202, 344, 407) df = data.frame(x, y) x y 1 aa 101 2 aa 102 3 aa 113 4 bb 201 5 cc 202 6 cc 344 7 cc 407 df %>% fi
x <- c("aa", "aa", "aa", "bb", "cc", "cc", "cc")
y <- c(101, 102, 113, 201, 202, 344, 407)
df = data.frame(x, y)
x y
1 aa 101
2 aa 102
3 aa 113
4 bb 201
5 cc 202
6 cc 344
7 cc 407
df %>%
filter(y != grep("^1"))
但是我在grep(“^1”)中遇到了一个
错误:缺少参数“x”,没有默认值
您需要仔细检查grepl
和过滤器的文档
对于grep
/grepl
,您还必须提供要签入的向量(在本例中为y),并且filter
采用逻辑向量(即,您需要使用grepl
)。如果要提供索引向量(从grep
),可以使用slice
df %>% filter(!grepl("^1", y))
或者使用源自grep
的索引:
df %>% slice(grep("^1", y, invert = TRUE))
但您也可以只使用substr
,因为您只对第一个字符感兴趣:
df %>% filter(substr(y, 1, 1) != 1)
通过组合使用dplyr
和stringr
(保持在tidyverse内),您可以执行以下操作:
df %>% filter(!str_detect(y, "^1"))
这是因为str\u detect
返回一个逻辑向量。感谢您的澄清!我错误地假设正则表达式会识别我想要从==”的左侧得到的向量。str\u detect
也有一个negate
参数,因此可以使用str\u detect(y,“^1”,negate=T)
!str_detect(y,“^1”)