2017-08-11 159 views
3

我想從我的數據框中刪除包含左括號行「(」如何刪除特殊字符的行?

我嘗試了以下內容:

df[!grepl("(", df$Name),] 

但這並不追查(標誌

+3

的'('用grep的表達正則表達式的一部分,而不是作爲一個字符理解儘量躲避開括號:。'\\(',看看這是否會工作,你可以找到更多細節在這裏:https://stackoverflow.com/questions/27721008/how-do-i-deal-with-special-characters-like-in-my-regex – Deena

+0

像這樣?df [!grepl(\\(, df $ Name),] – nemja

回答

6

你必須仔細逃脫(\\

x <- c("asdf", "asdf", "df", "(as") 

x[!grepl("\\(", x)] 
# [1] "asdf" "asdf" "df" 

剛剛申請日是你的DF像df[!grepl("\\(", df$Name), ]

你也可以考慮通過使用正則表達式刪除所有puctuation字符:

x[!grepl("[[:punct:]]", x)] 

正如@CSquare在評論中指出,here is a great summary about special characters in R regex


附加輸入從評論:
@Sotos:pattern='('fixed = TRUE獲得表現,因爲正則表達式可以被繞過。

x[!grepl('(', x, fixed = TRUE)] 
+2

我建議使用'fixed = TRUE'而不是轉義括號,即('x [!grepl('(',x,fixed = TRUE)]'),這將會更有效率因爲它繞過了正則表達式引擎 – Sotos

+0

'grep(「(」,x,fixed = TRUE,invert = TRUE,value = TRUE)' – jogo

+0

感謝提示,將它添加到A. – loki