Suppose I have the following SQL statement that I wish to save as a data.frame in R.
select "month_idx", "year", "month",
sum(case when "term_deposit" = 'Yes' then 1.0 else 0.0 end) as subscribe,
count(*) as total
from "bank"
group by "month_idx", "year", "month"
Using an R-script this is easy, just wrap the code with dbGetQuery().
However, with the preview release of Rstudio functionality has been added so we can write SQL-scripts in SQL-files with code highlightning, autocomplete etc. So my workflow (which involves a lot of SQL) is this: I type the SQL-code in a separate SQL-script in RStudio, much like I did with Visual Studio before, then I copy the SQL-code to an R-script that uses dbGetQuery() and saves it as a data.frame.
But I am OBSESSED with elminiating copy & paste actions in my workflow. Is there a way to save a query from SQL-scripts to a data.frame in RStudio?
In my head it would be something like:
-- !preview conn=con, output.var = "df"
select "month_idx", "year", "month",
sum(case when "term_deposit" = 'Yes' then 1.0 else 0.0 end) as subscribe,
count(*) as total
from "bank"
group by "month_idx", "year", "month"
But that doesn't work. Anybody know if it's possible in any other way?
Sorry, maybe my question was not properly formulated.
What I want to do is to write SQL-scripts in SQL-files in RStudio (with proper formatting) and when I execute the queries (in the SQL-script in Rstudio) save the tables generated as data.frames in R without having to copy the SQL-code to dbGetQuery.
One way to work with R-scripts och SQL-scripts separated, I found, is to save the SQL-query to a file, my-sql.sql and then run this in the R-script: