Use double quotes within double quotes in R

To use double quotes within double quotes in R, use the backslash in front of each quote surrounding your text. It will look like:

\"Type\"

While you can typically get the same result by using single quotation marks instead of double, there may be situations where single doesn’t cut it. I ran into this issue recently using the package sqldf to utilize SQL code in R. The specific code I was using broke if I used single quotation marks, so I used this workaround instead.

An example of what this looks like in a SQL SELECT statement:

my_data <- sqldf("SELECT * FROM table WHERE month = \"January\" AND id = 1")

Example

Here is a full example using test data with the statement above. The output my_data includes the double quotes within double quotes, and my_data2 shows the same result with single quotes.

#Double quotes within double quotes

#load packages
suppressPackageStartupMessages(library(pacman))
pacman::p_load(tidyverse, sqldf)

#create example data
ex_data <- tibble(
  id = c(1, 2, 3, 4),
  month = c("January", "February", "January", "March"))

my_data <- sqldf("SELECT * FROM ex_data WHERE month = \"January\" AND id = 1")
my_data2 <- sqldf("SELECT * FROM ex_data WHERE month = 'January' AND id = 1")

Leave a Comment

Your email address will not be published. Required fields are marked *