str_replace (package stringr) cannot replace brackets in r? -


i have string, say

 fruit <- "()goodapple" 

i want remove brackets in string. decide use stringr package because can handle kind of issues. use :

str_replace(fruit,"()","") 

but nothing replaced, , following replaced:

[1] "()good" 

if want replace right half bracket, works:

str_replace(fruit,")","")  [1] "(good" 

however, left half bracket not work:

str_replace(fruit,"(","") 

and following error shown:

error in sub("(", "", "()good", fixed = false, ignore.case = false, perl = false) :   invalid regular expression '(', reason 'missing ')'' 

anyone has ideas why happens? how can remove "()" in string, then?

escaping parentheses it...

str_replace(fruit,"\\(\\)","") # [1] "goodapple" 

you may want consider exploring "stringi" package, has similar approach "stringr" has more flexible functions. instance, there stri_replace_all_fixed, useful here since search string fixed pattern, not regex pattern:

library(stringi) stri_replace_all_fixed(fruit, "()", "") # [1] "goodapple" 

of course, basic gsub handles fine too:

gsub("()", "", fruit, fixed=true) # [1] "goodapple" 

Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -