Search code examples
rdataframegsubapostrophe

Gsub apostrophe in data frame R


I need to remove all apostrophes from my data frame but as soon as I use....

textDataL <- gsub("'","",textDataL)

The data frame gets ruined and the new data frame only contains values and NAs, when I am only looking to remove any apostrophes from any text that might be in there? Am I missing something obvious with apostrophes and data frames?


Solution

  • To keep the structure intact:

     dat1 <- data.frame(Col1= c("a woman's hat", "the boss's wife", "Mrs. Chang's house", "Mr Cool"),
     Col2= c("the class's hours", "Mr. Jones' golf clubs", "the canvas's size", "Texas' weather"),
     stringsAsFactors=F)
    

    I would use

         dat1[] <- lapply(dat1, gsub, pattern="'", replacement="")
    

    or

         library(stringr)
         dat1[] <- lapply(dat1, str_replace_all, "'","")
     dat1
    #                Col1                 Col2
    # 1      a womans hat     the classs hours
    # 2    the bosss wife Mr. Jones golf clubs
    # 3 Mrs. Changs house     the canvass size
    # 4           Mr Cool        Texas weather