If you have more than one table, use dm.
Create dm…
Add keys: dm_add_pk()
, dm_add_fk()
Automatic for MariaDB, SQL Server, Postgres, and others.
Primary keys
Identify potential primary keys:
-
dm_enum_pk_candidates()
: columns, candidate, why.
Identify potential foreign keys:
-
dm_enum_fk_candidates()
: columns, candidate, why.
dm objects: relational data models
The dm package provides a grammar of relational data models. It helps maintain referential integrity.
A dm behaves like a list of tables (data frames or lazy tables) capturing relationships between the tables.
Shiny app: dm_gui(dm = dm1)
Visualize dm:
dm_draw()
Control diagram level of detail: display…
- Only keys (default):
dm_draw(view_type = "keys_only")
. - All variables:
dm_draw(view_type = "all")
. - Only table names:
dm_draw(view_type = "title_only")
.
Control diagram scope
To visualize fewer tables first use dm_select_tbl()
.
Transform dm into tibble
Wide tibble: Cascade joins with
dm_flatten_to_tbl()
Only direct neighbours: dm_flatten_to_tbl()
All neighbours: dm_flatten_to_tbl(.recursive = TRUE)
Single tibble dm: dm_wrap_tbl()
Parent tables are packed — dm_pack_tbl()
.
Child tables are nested — dm_nest_tbl()
.
Mutate, create, analyze tables
Method 1: deconstruct and reconstruct
-
dm_get_tables(keyed = TRUE)
:
to keep information on primary and foreign keys).
- tidyverse pipeline on the table of interest.
- Optional: update the dm object:
Method 2: zoom
-
dm_zoom_to()
: Zoom on a table.
- tidyverse pipeline (
mutate()
, etc.).
-
dm_update_zoomed()
(replace) /dm_insert_zoomed()
Insert, update or remove rows in a dm
Methods:
-
dm_rows_insert(dm1, dm2)
: adds new rows -
dm_rows_update(dm1, dm2)
: changes values in rows -
dm_rows_patch(dm1, dm2)
: fills in missing values -
dm_rows_upsert(dm1, dm2)
: adds new or changes rows -
dm_rows_delete(dm1, dm2)
: deletes rows
dm1 |>
dm_rows_insert(dm2, in_place = FALSE)
dm1 |>
dm_rows_insert(dm2, in_place = TRUE)
A dm is immutable, except with
- these functions AND
- a mutable backend (database) AND
-
in_place = TRUE
.