How ggdag and dagitty work together
mainggdag is designed to work with the dagitty package. It provides a tidyverse-friendly interface to create, analyze, and plot causal directed acyclic graphs (DAGs).
You can use ggdag in two primary ways:
- Tidying existing
dagittyobjects: Usetidy_dagitty(dag)to convert adagittyobject into a tidy data frame suitable forggplot2. - Creating DAGs with R-like syntax: Use the
dagify()function to define causal relationships using formula syntax, which is more intuitive for R users than thedagittystring syntax.
To retrieve the original DAG object from a tidied object, use pull_dag(). To retrieve the underlying data frame, use pull_dag_data().
library(ggdag)
library(ggplot2)
# Example: Creating a DAG using dagify syntax
tidy_ggdag <- dagify(
y ~ x + z2 + w2 + w1,
x ~ z1 + w1 + w2,
z1 ~ w1 + v,
z2 ~ w2 + v,
w1 ~ ~w2, # bidirected path
exposure = "x",
outcome = "y",
coords = time_ordered_coords()
) |>
tidy_dagitty()