2016-11-09 66 views
0

這是我的數據集不grep的使用功能工作「(」

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  

我想提取所有的行包含(direct)/(none)

,我寫了下面的代碼:

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

但是它的輸出結果爲0,與其他產品如google/cpc有什麼不同?這是否是「(」?

這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)) 
+2

你可以使用'grep'跳過所有,如果只是尋找一個直接匹配'DF [DF $源==「(直接)/(無)」]' – thelatemail

+0

對不起也許我的例子不是易潔我想要所有包含「(直接)/(無)」的行。例如,如果一個用戶的源是l,(直接)/(無),a,b,c,我也需要這個 – MFR

回答

3

(a special meaning in regex。您應該逃避它\\(

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

或使用fixed = TRUE告訴grep解釋模式原樣。

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

謝謝。第一個選項並不完美,我通過使用第二個選項得到了這個錯誤:「unused argument(fixed = TRUE)」 – MFR

+0

你把'fixed = TRUE'放在正確的位置嗎?這絕對是'grep'的一個參數。 – Hugh