library(DBI)
library(RSQLite)
library(dplyr)
How to run SQL in Quarto
Quarto
SQL
R
Configure to run SQL sentences inside Quarto Documents
1 Install the following R packages
```{r}
install.packages(c('rmarkdown', 'knitr', 'DBI', 'RSQLite', 'dplyr'))
install.packages('dbplyr', dependencies = TRUE)
```
2 Import the libraries in R
3 Create the connection to the database
In this case I’m using SQLite in memory that wont create a file. And also, I’ll use the dataset mtcars
included in the R packages.
<- DBI::dbConnect(RSQLite::SQLite(),
con dbname = ":memory:")
copy_to(dest = con,
df = mtcars,
name = "mtcars")
dbListTables(con)
[1] "mtcars" "sqlite_stat1" "sqlite_stat4"
Note
In this point we are ready to start SQL executions in this Quarto document.
4 Select
We start applying a Select sentence on the database mtcars
created in the step before.
SELECT * FROM mtcars;
mpg | cyl | disp | hp | drat | wt | qsec | vs | am | gear | carb |
---|---|---|---|---|---|---|---|---|---|---|
21.0 | 6 | 160.0 | 110 | 3.90 | 2.620 | 16.46 | 0 | 1 | 4 | 4 |
21.0 | 6 | 160.0 | 110 | 3.90 | 2.875 | 17.02 | 0 | 1 | 4 | 4 |
22.8 | 4 | 108.0 | 93 | 3.85 | 2.320 | 18.61 | 1 | 1 | 4 | 1 |
21.4 | 6 | 258.0 | 110 | 3.08 | 3.215 | 19.44 | 1 | 0 | 3 | 1 |
18.7 | 8 | 360.0 | 175 | 3.15 | 3.440 | 17.02 | 0 | 0 | 3 | 2 |
18.1 | 6 | 225.0 | 105 | 2.76 | 3.460 | 20.22 | 1 | 0 | 3 | 1 |
14.3 | 8 | 360.0 | 245 | 3.21 | 3.570 | 15.84 | 0 | 0 | 3 | 4 |
24.4 | 4 | 146.7 | 62 | 3.69 | 3.190 | 20.00 | 1 | 0 | 4 | 2 |
22.8 | 4 | 140.8 | 95 | 3.92 | 3.150 | 22.90 | 1 | 0 | 4 | 2 |
19.2 | 6 | 167.6 | 123 | 3.92 | 3.440 | 18.30 | 1 | 0 | 4 | 4 |
5 Apply a SUM functions in one of the columns
SELECT SUM(mpg) FROM mtcars;
SUM(mpg) |
---|
642.9 |
6 Apply a distinct in one column
SELECT distinct(cyl) FROM mtcars;
cyl |
---|
6 |
4 |
8 |
7 Personal notes
Creating this blog I discover the following things:
SQL
interface in quarto only acceptsSELECT
statements- This requires
rmarkdown
andknitr
R libraries installed - The package
dplyr
is to use the functioncopy_to()
References
Special thanks to the following links: