1

I have the following string:

c(\"Yes \", \" No\")

I want to remove the backslashes such that it becomes:

c("Yes", "No)

I tried the following, as suggested here:

gsub("\\","", "c(\"Yes \", \" No\")", fixed = TRUE)

But it does not work, so I must have misunderstood something.

syntheso
  • 437
  • 3
  • 17

2 Answers2

0

It is a double quote, so either remove the quote and replace with blank

gsub('"',"", "c(\"Yes \", \" No\")", fixed = TRUE)
#[1] "c(Yes ,  No)"

or replace with a single quote

gsub('"',"'", "c(\"Yes \", \" No\")", fixed = TRUE)
#[1] "c('Yes ', ' No')"

If we print with cat, the character \ doesn't exist

cat("c(\"Yes \", \" No\")")
#c("Yes ", " No")


nchar('\"')
#[1] 1

cat('\"')
#"
akrun
  • 874,273
  • 37
  • 540
  • 662
0

The quoted character string literal "c(\"Yes \"…)" does not contain backslashes. It contains escaped double quotes. The escape char backslashes are displayed (only) when printing the value in R (which happens automatically when executing the value in the R console). But they are not in the actual string, and saving, displaying or otherwise handling the string won’t see them.

For instance, you can show the true string value via the message function:

message("c(\"Yes \", \" No\")")

Outputs:

c("Yes ", " No")

And, just to make it even clearer, gsub does not require special handling of backslashes in strings. String literals do, because backslash is the escape character.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214