Handling quotation marks in sqldf

半城伤御伤魂 提交于 2019-12-10 11:59:30

问题


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


来源:https://stackoverflow.com/questions/18686083/handling-quotation-marks-in-sqldf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!