I am curious. In SQL script file, I can only preview the SQL document, but not saving the data into R environment.
In SQL file:
-- !preview conn=DBI::dbConnect(drv = RSQLite::SQLite(),dbname = ".../SQL Files/sql_starter.sqlite")
SELECT cut, AVG(price) as ave_price
FROM diamonds
GROUP BY cut
Unlike in R markdown where you can actually save the output via output.var argument.
SELECT cut, AVG(price) as ave_price
FROM diamonds
GROUP BY cut
Output:
> ave_price
cut ave_price
1 Fair 4358.758
2 Good 3928.864
3 Ideal 3457.542
4 Premium 4584.258
5 Very Good 3981.760
Is there any way to retrieve the data? I am still fairly new in using SQL in R/RStudio.
If you are asking how to run that sql code and have it result in a data.frame in the R environment, then I would just consider it a text source of query, and write the R code that can run that code on a given database connection.
for example if the sql script was called "test_1.sql"
then in some other R or Rmarkdown script you could have code like :
# sql script to queryable text
f1 <- file("test_1.sql","r")
q1 <- readLines(f1)
close(f1)
q2 <- paste0(q1,collapse = "\n")
conn <- DBI::dbConnect(RSQLite::SQLite()) # or some other connection
(result_df1 <- DBI::dbGetQuery(conn,q2))