在dplyr中结合grepl过滤观察结果

jal*_*pic 33 r filter dplyr grepl

我试图找出如何使用dplyr和过滤大型数据集中的一些观察结果grepl.grepl如果其他解决方案更优化,我不会坚持.

拿这个样本df:

df1 <- data.frame(fruit=c("apple", "orange", "xapple", "xorange", 
                          "applexx", "orangexx", "banxana", "appxxle"), group=c("A", "B") )
df1


#     fruit group
#1    apple     A
#2   orange     B
#3   xapple     A
#4  xorange     B
#5  applexx     A
#6 orangexx     B
#7  banxana     A
#8  appxxle     B
Run Code Online (Sandbox Code Playgroud)

我想要:

  1. 过滤掉以'x'开头的那些案例
  2. 过滤掉那些以'xx'结尾的案例

我已经设法弄清楚如何摆脱包含'x'或'xx'的所有东西,但不是以开头或结尾.这里是如何摆脱内部'xx'的一切(不仅仅是结束):

df1 %>%  filter(!grepl("xx",fruit))

#    fruit group
#1   apple     A
#2  orange     B
#3  xapple     A
#4 xorange     B
#5 banxana     A
Run Code Online (Sandbox Code Playgroud)

这显然是"错误的"(从我的角度来看)过滤了'appxxle'.

我从来没有完全掌握正则表达式.我一直在尝试修改代码,例如: grepl("^(?!x).*$", df1$fruit, perl = TRUE) 尝试使其在filter命令中工作,但我不太明白.

预期产量:

#      fruit group
#1     apple     A
#2    orange     B
#3   banxana     A
#4   appxxle     B
Run Code Online (Sandbox Code Playgroud)

dplyr如果可能的话,我想在里面做这件事.

Cha*_*ase 43

我不明白你的第二个正则表达式,但这个更基本的正则表达式似乎可以解决这个问题:

df1 %>% filter(!grepl("^x|xx$", fruit))
###
    fruit group
1   apple     A
2  orange     B
3 banxana     A
4 appxxle     B
Run Code Online (Sandbox Code Playgroud)

我假设你知道这一点,但你根本不需要dplyr在这里使用:

df1[!grepl("^x|xx$", df1$fruit), ]
###
    fruit group
1   apple     A
2  orange     B
7 banxana     A
8 appxxle     B
Run Code Online (Sandbox Code Playgroud)

正则表达式正在寻找以xOR结尾的字符串xx.的^$分别是针对字符串的开头和结尾的正则表达式锚.|是OR运算符.我们否定的结果grepl!如此我们发现字符串不匹配什么是正则表达式中.

  • @GabrielReis - 这可能是在 2020 年......在 2014 年最初回答时,dplyr 并不总是那么快。 (2认同)