Ty Voss
Ty Voss

Reputation: 283

Issue with a column containing special characters

I have dataframe in R that contains a column of type character with values as follows

"\"121.29\""
"\"288.1\""
"\"120\""
"\"V132.3\""
"\"800\""

I am trying to get rid of the extra " and \ and retain clean values as below

121.29
288.10
120.00
V132.30
800.00

I tried gsub("([\\])","", x) also str_repalce_all function so far no luck. I would much appreciate it if anybody can help me resolve this issue. Thanks in advance.

Upvotes: 0

Views: 47

Answers (1)

RHertel
RHertel

Reputation: 23798

Try

gsub('\\"',"",x)
[1] "121.29" "288.1"  "120"    "V132.3" "800" 

Since the fourth entry is not numeric and an atomic vector can only contain entries of the same mode, the entries are all characters in this case (the most flexible mode capable of storing the data). So there still will be quotes around each entry.

Because \ is a special character, it needs to be escaped with a backslash, so the expression \\" is passed as a first parameter to gsub(). Moreover, as suggested by @rawr, one can use single quotes to address the double quote. An alternative would be to use double quotes and escape them, too:

gsub("\\\"","",x)

which yields the same result.

Hope this helps.

Upvotes: 2

Related Questions