正则表达式(RegEx)和dplyr :: filter()

43

我有一个简单的数据框,长得像这样:

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

我想使用dplyr :: filter()和RegEx来过滤掉所有以数字1开头的y观察结果。

我想象代码会像这样:

df %>%
  filter(y != grep("^1")) 

但是我遇到了一个 Error in grep("^1") : argument "x" is missing, with no default

2个回答

59

你需要仔细检查关于greplfilter的文档。

对于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)

1
谢谢澄清!我错误地认为正则表达式会从“==”的左侧识别出我想要的向量。 - emehex

35

使用 dplyrstringr 的组合(以保持在 tidyverse 内),你可以做到:

df %>% filter(!str_detect(y, "^1"))

这个方法能够起作用是因为str_detect会返回一个逻辑向量。


5
str_detect函数还有一个negate参数,因此您可以使用str_detect(y, "^1", negate=T)代替!str_detect(y, "^1") - filups21

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接