'How do I force r to print character strings with single quotes?
I'm writing some code that interfaces with SQL, and I need my character strings to print with single quotes, but R defaults to double quotes. When I go to ?Quotes, I don't see any guidance.
Any suggestions on how I can get the below character string to print as I'm typing it (with single quotes)?
help <- 'help me'
help
#Result :`-(
"help me"
Solution 1:[1]
Creating valid SQL statements programmatically is a common task in R. So, it is no surprise that there are already solutions available. Just to pick 2 Examples:
1. sqldf
This example is taken from G. Grothendiek's sqldf overview:
library(sqldf)
minSL <- 7
limit <- 3
species <- "virginica"
fn$sqldf("select * from iris where \"Sepal.Length\" > $minSL and species = '$species' limit $limit")
Sepal.Length Sepal.Width Petal.Length Petal.Width Species 1 7.1 3.0 5.9 2.1 virginica 2 7.6 3.0 6.6 2.1 virginica 3 7.3 2.9 6.3 1.8 virginica
2. glue
This example is modified from help("glue_sql", "glue"):
library(glue)
library(magrittr)
con <- DBI::dbConnect(RSQLite::SQLite(), ":memory:")
iris2 <- iris
colnames(iris2) <- gsub("[.]", "_", tolower(colnames(iris)))
DBI::dbWriteTable(con, "iris", iris2)
var <- "sepal_width"
tbl <- "iris"
num <- 2
val <- "setosa"
glue_sql("
SELECT {`var`}
FROM {`tbl`}
WHERE {`tbl`}.sepal_length > {num}
AND {`tbl`}.species = {val}
LIMIT {limit}
", limit = 4, .con = con) %T>%
print()%>%
DBI::dbGetQuery(con, .)
<SQL> SELECT `sepal_width` FROM `iris` WHERE `iris`.sepal_length > 2 AND `iris`.species = 'setosa' LIMIT 4 sepal_width 1 3.5 2 3.0 3 3.2 4 3.1
3. Other ressources
Perhaps, it might be worthwhile to study the help pages on SQL quoting (?DBI::SQL), or more low level: sprintf().
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Uwe |
