How to remove single quote from a string in R?

18,087

Solution 1

To replace text, use (g)sub:

result <- gsub("'", '', yourString)

The function is vectorised so you can apply it directly to your data frame without the need for a loop or an apply:

df$X2 <- gsub("'", '', df$X2)

Solution 2

 df[,2] <- gsub("'", '', df[,2], fixed=TRUE)

I think fixed is the default, but it never hurts to be explicit.

Apologies, read the title of the post as "How to remove (one) single quote from a string in R?"

Solution 3

I know the question states otherwise, but what he actually wants to do is to unwrap this 2nd column, that is to remove tailing and leading single quotes. This can be done with a slightly enhanced regex:

gsub("(^')|('$)", "", df$X2)
Share:
18,087

Related videos on Youtube

phoenix
Author by

phoenix

Updated on June 04, 2022

Comments

  • phoenix
    phoenix almost 2 years

    In a data frame I have text like

    "X1" "X2"
    "1" 53 "'[email protected]'"
    "2" 54 "'[email protected]'"
    "3" 55 "'[email protected]'"
    "4" 56 "'[email protected]'"
    

    How do I remove the single quotes from the string in 2nd column?

  • Konrad Rudolph
    Konrad Rudolph almost 11 years
    fixed=TRUE is not the default but in this case it makes no difference. However, sub alone won’t work here, OP needs gsub.