library(CausalStructures)

Getting Started
Source: vignettes/CausalStructures.qmd
This guide shows the basic usage of CausalStructures with directed acyclic graphs (DAGs).
Constructing a graph
Let’s build a DAG with a confounder A that affects both X and Y, and a mediator M between X and Y:
Each edge is written with an operator such as %-->%, %<->% or %o-o% (see edge operators), and + fans an edge out to, or in from, several nodes at once. class says which kind of graph it is; "DAG" is the default (see Graph Classes for the others).
Every graph is checked against the structural constraints of its class when you construct it. For a DAG, this means all edges are directed (%-->%) and there are no cycles. Let’s try to create a DAG with a cycle:
Since a picture is worth a thousand words1, let’s plot our DAG:
plot(dag)
For more plotting details and customization options, see Plotting Causal Graphs.
Testing conditional independence
A central question in causal inference is whether two variables are conditionally independent. For DAGs, this is determined using d-separation.
Are X and Y independent?
d_separated(dag, "X", "Y")
#> [1] FALSENo, there is a directed path X --> M --> Y.
If we condition on the mediator M, does that make them independent?
d_separated(dag, "X", "Y", given = "M")
#> [1] FALSEStill no, the backdoor path via A, X <-- A --> Y, remains open.
What if we condition on both A and M?
d_separated(dag, "X", "Y", given = c("A", "M"))
#> [1] TRUEYes, now all paths are blocked.
Finding adjustment sets
Now suppose we want to estimate the causal effect of X on Y. The backdoor path X <-- A --> Y introduces confounding bias, so we need to block it by conditioning on a valid adjustment set.
Let’s find one automatically:
adjustment_set(dag, "X", "Y")
#> [1] "A"We can also verify that a specific set is valid:
is_valid_adjustment(dag, "X", "Y", "A")
#> [1] TRUEAnd enumerate all minimal valid adjustment sets:
all_adjustment_sets(dag, "X", "Y")
#> [[1]]
#> [1] "A"In this case, {A} is the only minimal set that blocks the confounding.
Next steps
This quick guide barely scratched the surface of what you can do with this package:
- For more on working with DAGs in the context of causal identification, see Causal Identification.
- For what each graph class means and how to build one, see Graph Classes; for working with equivalence classes, see Equivalence Classes and PAG Causal Effects.
- To customize plots, see Plotting Causal Graphs.
Footnotes
Especially with causal graphs.↩︎