Skip to content

About

Graph-based causal analysis in R.

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

causaliflower

causality + cauliflower = 'causaliflower'!

Build, edit and assess causal graphs in R with causaliflower. The package extends dagitty and ggdag to support reproducible causal analysis, with a focus on agriculture.

Installation

The most recent version can be installed from GitHub:

if (!require("pak")) {
  install.packages("pak")
}

pak::pak("AAGI-AUS/causaliflower")

Note: Development version 0.0.2.9000 requires dagitty exactly 0.3.4. Installing from source also requires a C++17 compiler.

See the introductory vignette vignette("causaliflower-introduction") or examples below.

Example code

Build a DAG for a crop treatment and outcome using the bundled structural causal model derived from APSIM. Barley, wheat and maize are supported.

Start with a recipe that names the crop, treatment, outcome and whether the treatment was randomised. dagby() records these choices without running the query. The default size = "smallest" requests a compact DAG:

library(causaliflower)

recipe <- dagby(
  crop = "barley",
  treatments = "nitrogen_applied",
  outcomes = "grain_protein",
  randomised_treatment = FALSE,
  size = "smallest"
)

recipe

crop_dag <- recipe |>
  dagby_query() |>
  dagby_construct()

plot_dagitty(crop_dag)

dagby_query() builds the source graph. dagby_construct() then uses the recipe's settings to select and check a DAG. To change its size, set size = "largest" or a numeric variable count directly in dagby(), or override it in dagby_construct(). Size counts source variables, which can appear at several time occasions or as more than one drawn node.

Use keep_nodes in the recipe to retain particular variables and latents to declare unmeasured variables. Construction otherwise treats all variables as observed. Specialist query controls remain available through params = dagby_query_params(...).

Read the adjustment checks with dagby_checks(crop_dag). Use dagby_options(crop_dag) to inspect the size and known alternatives. dagby_source(crop_dag) retrieves the source query, and dagby_temporal(crop_dag) retrieves the graph with separate time occasions.

Build a basic graph (dagitty object):

variables <- c("X3", "X2", "X1")
treatments <- "T"
outcomes <- "Y"


dag <- build_graph(variables = variables,
                   treatments = treatments,
                   outcomes = outcomes,
                   type = "ordered")
  • full uses bidirected edges following the ESC-DAGs Mapping Stage in Ferguson et al. (2020).
  • chain connects adjacent temporal positions within each role except instrumental variables and adds no arrows between roles apart from explicit latent targets and instrument edges.
  • last adds arrows between roles from the last position of the sending role to the first position of the receiving role, and first sends them from the first position instead.
  • ordered connects every earlier position to every later position within each role except instrumental variables.
  • saturated also adds the directed arrows allowed by the package's order of causal roles.

Use a list element to place nodes at the same temporal position:

dag <- build_graph(
  variables = variables,
  treatments = treatments,
  outcomes = outcomes,
  mediators = list("M1", c("M2", "M3"), "M4"),
  type = "last"
)

Plot dagitty objects:

plot_dagitty(dag)

# Add coordinates to a dagitty object (more detail below)
dag <- add_coords(dag)

Generate new coordinates:

# Changing the input parameters affects how coordinates are generated
dag <- add_coords(dag,
                  x_step = 2, # horizontal spacing between node columns
                  y_step = 1) # vertical spacing between nodes in the same column

Add edges to existing nodes:

full_graph <- connect_nodes(dag, type = "full")
full_graph |> plot_dagitty()

saturated_graph <- connect_nodes(dag, type = "saturated", print_edges = TRUE)

Assess graph edges using causal criteria:

## Assess edges to keep and build a new graph
new_graph <- full_graph |>
  assess_edges(keep_edges = dag,
               assess_causal_criteria = TRUE) |> # guided causal criteria sequence
  keep_edges(dag = full_graph)


plot_dagitty(new_graph)

## Or, save answers to causal criteria in a list
edges_list <- full_graph |>
  assess_edges(keep_edges = dag,
               assess_causal_criteria = TRUE,
               save_answers = TRUE) # saves answers to causal criteria, output becomes a list

edges_list$edges
edges_list$answers

Join two dagitty objects, keeping the coordinates of the first:

mediators <- "M"

new_dag <- build_graph(treatments = treatments,
                       outcomes = outcomes,
                       mediators = mediators,
                       type = "last")

new_dag <- add_coords(new_dag)
plot_dagitty(new_dag)

dag <- join_graphs(dag, new_dag)
plot_dagitty(dag)

Check if the effects are identifiable:

get_identification(dag)
  • Use id_status = "all" to include unsuccessful strategy checks.
  • Identification depends on the supplied graph and the assumptions stated with each result.

Find single door sets for the direct path coefficient in a linear model (returns up to five sets, ordered by size):

minimal_sets(dag, effect = "direct")

Add nodes to an existing graph:

nodes <- c("X4", "X5")
children <- names(dag)

dag <- add_nodes(dag, nodes, children = children)
plot_dagitty(dag)

Place new nodes by causal role and temporal position:

dag <- add_nodes(
  dag,
  nodes = "W",
  role = "confounder",
  type = "saturated",
  position = first()
)
plot_dagitty(dag)

For position, use the four placement helpers below, alone or combined with c(). You can also supply strings, such as position = "first" or position = c(after = "X2").

first()       # before every existing node
last()        # after every existing node
before("T")   # immediately before an existing anchor node
after("X2")   # immediately after an existing anchor node

# Choose a position for each named new node.
dag <- add_nodes(
  dag,
  nodes = c("W1", "W2", "U"),
  role = "confounder",
  type = "saturated",
  position = c(first("W1"), after("X2", "W2"))
)

Choose which nodes receive and send arrows generated between roles:

dag <- build_graph(
  variables = variables,
  treatments = treatments,
  outcomes = outcomes,
  mediators = c(incoming("M1"), "M2", outgoing("M3")),
  type = "ordered"
)

Copy a node into successive positions:

dag <- copy_nodes(dag, "M2", copy_suffix = c("survey", "harvest"))

Get edges and node structure information from a dagitty object:

get_edges(dag)

get_node_edges(dag)

get_paths(dag)

get_structure(dag)

get_nodes(dag)

get_roles(dag)

get_diff_roles(dag, new_dag)

get_diff_edges(dag, new_dag)

Other utility functions:

confounders(dag)

mediators(dag)

instruments(dag)

colliders(dag)

competing_causes(dag)

mediator_outcome_confounders(dag)

proxies(dag)

If you have any questions, suggestions, or would like to contribute, please let me know!

About

Graph-based causal analysis in R.

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages