Skip to main content

Simulate data from a DAG

Source: R/data.R

Description

Simulates observational data from a linear Gaussian structural causal model over cg. Each node is a linear function of its parents plus independent Gaussian noise with standard deviation error_sd, with edge coefficients drawn uniformly from coef_range. If standardize = TRUE (default), each variable is standardized to zero mean and unit variance.

Usage

simulate_data(
  cg,
  n,
  standardize = TRUE,
  coef_range = c(-1, 1),
  random_sign = FALSE,
  error_sd = 1,
  seed = NULL
)

Arguments

cg A DAG created with cgraph().
n Number of samples to generate.
standardize If TRUE (default), standardize each variable to zero mean and unit variance.
coef_range Length-2 numeric vector giving the range edge coefficients are drawn uniformly from.
random_sign If TRUE, draw each coefficient’s magnitude from coef_range and its sign independently at random, instead of drawing the signed coefficient from coef_range.
error_sd Standard deviation of each node’s Gaussian noise term, or a length-2 range each node’s standard deviation is drawn uniformly from.
seed Optional integer seed for reproducibility.

Details

A sign-symmetric coefficient range such as c(-1, 1) puts many coefficients near zero, i.e. near-unfaithful edges. To keep every edge’s coefficient away from zero, use a positive range with random_sign = TRUE, e.g. coef_range = c(0.5, 2).

Value

A data frame with n rows (samples) and one column per node, named and ordered as in nodes().

Examples

dag <- cgraph(A %-->% B, B %-->% C)
data <- simulate_data(dag, n = 100, seed = 1405)
head(data)
#>            A           B          C
#> 1 -0.9566120  2.01171565  1.3009630
#> 2 -0.3166224 -0.47117119 -0.3889609
#> 3  0.7540757  1.42932584  0.5786812
#> 4  1.5430243  0.07776775 -1.0063268
#> 5 -0.7800137  0.25383534  0.7724043
#> 6 -0.6447593 -1.03127050  1.6590918

dag <- cgraph(A %-->% B, B %-->% C)
data2 <- simulate_data(
  dag,
  n = 100,
  standardize = FALSE,
  coef_range = c(0.5, 2),
  random_sign = TRUE,
  error_sd = c(0.5, 1.5),
  seed = 1405
)
head(data2)
#>            A          B          C
#> 1 -0.8521506 -2.5226754 -0.5858974
#> 2  0.5878833  0.2122126 -0.3005096
#> 3 -1.4276055 -0.2497187 -1.2629442
#> 4  0.5175274  0.2186455  0.7158205
#> 5 -1.4146574 -0.2275938 -0.3335240
#> 6 -2.7292475 -1.7414247 -1.8961214