Skip to main content

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:

dag <- cgraph(A %-->% X + Y, X %-->% M %-->% Y, class = "DAG")
dag
#> DAG with 4 nodes and 4 edges:
#>   nodes: A, M, X, Y
#>   edges:
#>     A --> X, A --> Y, X --> M, M --> 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).

NoteValidation on construction

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:

invalid_dag <- cgraph(A %-->% B %-->% C %-->% A)
#> Error:
#> ! Invalid DAG:
#>   - directed cycles are not allowed in DAG

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] FALSE

No, 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] FALSE

Still 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] TRUE

Yes, 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] TRUE

And 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:

Footnotes

  1. Especially with causal graphs.↩︎