【发布时间】:2014-11-17 22:03:32
【问题描述】:
我正在尝试研究如何使用 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
我想:
- 过滤掉以“x”开头的情况
- 过滤掉那些以“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
这显然是“错误地”(在我看来)过滤了“appxxle”。
我从来没有完全掌握正则表达式。我一直在尝试修改代码,例如:grepl("^(?!x).*$", df1$fruit, perl = TRUE) 以尝试使其在 filter 命令中工作,但我不太明白。
预期输出:
# fruit group
#1 apple A
#2 orange B
#3 banxana A
#4 appxxle B
如果可能的话,我想在dplyr 内执行此操作。
【问题讨论】: