Skip to contents

Simulate correlated Gaussian variables

Usage

simulate_correlated(
  n,
  means,
  sds = 1,
  rho = 0,
  structure = c("independent", "exchangeable", "ar1", "custom"),
  correlation = NULL,
  variable_names = NULL,
  seed = NULL,
  batch = NULL
)

Arguments

n

Number of observations.

means

Variable means.

sds

Variable standard deviations.

rho

Correlation used when correlation is not supplied.

structure

Correlation structure: one of "independent", "exchangeable", "ar1", or "custom". If left unset it is chosen from the other arguments: "custom" when correlation is supplied, "exchangeable" when a non-zero rho is supplied, and "independent" otherwise. Passing "independent" together with a non-zero rho is a contradiction and raises a simulab_contradictory_structure error.

correlation

A custom correlation matrix or tidy table returned by correlation_structure().

variable_names

Optional variable names.

seed

Optional random seed.

batch

Optional single positive whole number. When given, the simulator runs batch times and returns a plain list of batch results, each exactly what the same call without batch returns. With a seed, every dataset gets its own seed drawn from seed, so the whole batch is reproducible; without one the datasets are consecutive draws from the session's random-number stream. The default NULL returns a single result.

Value

A simulab_sim base data.frame with one row per observation and columns id and one column per variable. Three tidy tables come from as.data.frame(): what = "parameters" has one row per variable with columns variable, mean and sd; what = "correlation" and what = "covariance" each have one row per matrix cell with columns row, column and correlation or covariance. The covariance is the correlation matrix scaled by sds on both sides, so sds are standard deviations rather than variances.

Examples

simulate_correlated(
  n = 100,
  means = c(0, 1, 2),
  sds = c(1, 2, 1),
  rho = 0.4,
  structure = "exchangeable",
  seed = 1
)
#> <simulab_sim:correlated> 100 rows x 4 columns
#>    id         V1         V2         V3
#> 1   1 -0.6838367 -0.2759531  2.1185336
#> 2   2  0.4813996  1.5673797  3.6473458
#> 3   3 -0.7513606 -0.5967492  3.1248806
#> 4   4  1.4982380  1.6379158  2.0062187
#> 5   5 -0.2569962 -0.7931684 -0.2823676
#> 6   6  0.1158181  4.9089199  4.6860305
#> 7   7  0.7654131  2.7079731  2.9045594
#> 8   8  1.0317614  3.1207616  2.8791678
#> 9   9  0.6440032  1.9009305  2.1876256
#> 10 10  0.2346483  4.3605248  2.8663294
#> ... 90 more rows
#> 
#> Truth (parameters):
#>   variable mean sd
#> 1       V1    0  1
#> 2       V2    1  2
#> 3       V3    2  1
#> 
#> Other tables: correlation, covariance. Read one with as.data.frame(x, what = "correlation").