Handling quotation marks in sqldf

2019-06-10 01:21发布

问题:

I want to use sqldf and be able to write SQL statements exactly as they would be written in the sql command terminal.

For instance, here is a query from the manual:

Gavg <- sqldf("select g, avg(v) as avg_v from DF group by g")

If I were working with a separate SQL file, the query would be written:

select g,
avg(v) as avg_v
from "DF"
group by g

However, if I were to write this as:

Gavg <- sqldf("
    select g,
    avg(v) as avg_v
    from "DF"
    group by g
")

I would like to be able to copy/paste snippets of code into the area around sqldf(" ") without having to escape the quotation marks or having to reference an outside sql file that contains the command.

Is this possible?

回答1:

The easiest approach for your use case may just be writing some wrapper function that escapes all of those characters for you. For example something like this should work:

escape.quote <- function(){
  s <- paste(scan(what=character(),sep="\n"),collapse=" ")
  s <- gsub('"','\"',s)
  s <- gsub("'","\'",s)
  return(s)
} 

Then you can just insert this in your sqldf() calls and copy and paste your queries there. Like so:

> library(sqldf)
> set.seed(2)
> DF <- data.frame(g=rep(1:2,5),v=rnorm(10))
> sqldf(escape.quote())
1: select g,
2: avg(v) as avg_v
3: from "DF"
4: group by g
5: 
Read 4 items
  g      avg_v
1 1  0.6606215
2 2 -0.2383182


标签: sql r sqldf