Search code examples
rstringsubstring

How to remove "()" from data frame cells?


I am trying to clean my data from a data frame's cells. I want to remove some strings, but gsub somehow omits "()". My code:

getridof <- c("(a)", "(40X)", "(5X)", "(10X_a)", "(10X)", "(_)")

for (i in 1:length(getridof)) {
  df2$Sample <- gsub(getridof[i], "", df2$Sample)  
}

but "()" is left in cells after executing the script?


Solution

  • Using gsub:

    gsub("[()]", "", getridof)
    
    [1] "a"     "40X"   "5X"    "10X_a" "10X"   "_"  
    

    Using stringr:

    library(stringr)
    str_remove_all(getridof, "[()]")
    
    [1] "a"     "40X"   "5X"    "10X_a" "10X"   "_"