简体   繁体   English

grep函数不能与“(”一起使用吗?

[英]Doesn't grep function work with“(”?

This is my dataset 这是我的数据集

 userId               source           transactions
         (dbl)                      (chr)        (chr)              
1  1       google / cpc, google / cpc            0, 1            
2  2       (direct) / (none)                     0               
3  3       (direct) / (none)                     1               
4  4        google / organic, (direct) / (none)  0                 
5  5        google / organic                     0                  
6  6        google / organic                     0      

I want to extract all of the rows contain (direct) / (none) 我想提取包含(direct) / (none)所有行

and I wrote the following code: 我编写了以下代码:

output<-df[grep("(direct) / (none)", df$source),]

But it results in an out put with 0 observations, it work well with others such as google / cpc . 但结果是输出结果有0个观察值,与google / cpc等其他google / cpc配合也很好。 What is wrong? 怎么了? Is it the problem with "("? “(”是问题吗?

This is dput 这是dput

dput(df)
structure(list(userId = c(1, 2, 3, 
4, 5, 6, 7, 8, 
9, 10), source = c("google / cpc, google / cpc", 
"(direct) / (none)", "(direct) / (none)", "google / organic", 
"google / organic", "google / organic", "(direct) / (none)", 
"google / cpc, google / cpc, google / cpc, google / organic, google / cpc", 
"(direct) / (none)", "(direct) / (none)"), transactions = c("0, 1", 
"0", "1", "0", "0", "0", "0", "0, 0, 0, 0, 0", "0", "1")), .Names = c("userId", 
"source", "transactions"), class = c("tbl_df", "data.frame"
), row.names = c(NA, -10L))

( has a special meaning in regex . You should either escape it \\\\( ( 在regex中有特殊含义 。您应该对其进行转义\\\\(

grep("\\(direct\\) / \\(none\\)", df$source)

or use fixed = TRUE which tells grep to interpret the pattern as-is. 或使用fixed = TRUE告诉grep原样解释模式。

grep("(direct) / (none)", df$source, fixed = TRUE)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM