-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdbplyr-example.qmd
More file actions
69 lines (50 loc) · 1.28 KB
/
dbplyr-example.qmd
File metadata and controls
69 lines (50 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
---
title: "dbplyr demo"
format: html
editor: visual
---
## dbplyr!
*"Okay, cool, thanks for Intro to SQL. Now can I go back to coding in R?" -* 🧑🌾
```{r}
library(tidyverse)
library(dbplyr)
```
```{r}
library(duckdb)
library(DBI)
con <- DBI::dbConnect(
duckdb::duckdb(),
"data/GiBleed_5.3_1.1.duckdb"
)
```
Specify the dataframe of interest:
```{r}
person_db <- tbl(con, "person")
```
Now, you can query it. By default you get the first 1000 entries.
```{r}
person_db |>
select(person_id, birth_datetime, gender_source_value) |>
filter(gender_source_value == "F")
```
You can save your query as a variable:
```{r}
cool_query = person_db |>
select(person_id, birth_datetime, gender_source_value) |>
filter(gender_source_value == "F")
```
You can see what it is translating into SQL:
```{r}
cool_query |> show_query()
```
Finally, when you are ready to fully query it:
```{r}
cool_query_result = cool_query |> collect()
```
Do R things:
```{r}
cool_query_result$year <- as.numeric(sub("-.*", "", cool_query_result$birth_datetime))
ggplot(cool_query_result) + aes(x = year) + geom_histogram() + theme_bw()
```
Full Guide here: <https://dbplyr.tidyverse.org/articles/dbplyr.html>
- Yes, you can even do joins: <https://dbplyr.tidyverse.org/reference/join.tbl_sql.html>