Skip to contents

For use with Trial objects, this function makes it possible to easily add additional covariates to an existing random generator (function(n ...) returning a data.frame or data.table)

Usage

covar_join(f, ...)

Arguments

f

covariate random generator

...

additional covariate generators or constant covariates

Value

function, with returned data type matching that of f

Examples

# single period
n <- 5
c1 <- function(n) data.frame(a = rnorm(n))
c2 <- function(n) data.frame(b = rnorm(n))
x <- c1 %join% c2
x(n)
#>            a          b
#> 1 -0.3149336 -1.1457702
#> 2  0.5017690 -0.4570055
#> 3  0.3992236  0.5374717
#> 4 -0.5015149  1.6748761
#> 5  0.6283754 -0.5707314

# adding covariates that remain constant when sampling
x <- c1 %join% data.frame(b = rnorm(n))
all.equal(x(n)$b, x(n)$b)
#> [1] TRUE

# adding multiple anonymous functions require parenthesis enclosing, with
# the exception of the last function
x <- c1 %join%
 (\(n) data.frame(b = rnorm(n))) %join%
 \(n) data.frame(c = rnorm(n))
x(n)
#>             a           b          c
#> 1 -1.70602622 -0.01778903  0.4965845
#> 2  0.13690206  0.24343866  0.8841789
#> 3 -0.08016452  1.06749504  0.4612312
#> 4 -0.76433721  0.60605805 -0.3019586
#> 5  1.00512123 -1.25726945 -0.3872854

# multiple periods
base <- setargs(covar_loggamma, normal.cor = .5)
x <- base %join%
  function(n) list(
      data.frame(a = rbinom(n, 1, 0.5)),
      data.frame(a = rbinom(n, 1, 0.5))
    )
x(n)
#> $`0`
#>              z     a
#>          <num> <int>
#> 1:  1.19817935     1
#> 2: -0.21649025     1
#> 3: -1.06560979     0
#> 4: -0.16898785     0
#> 5: -0.09505867     1
#> 
#> $`1`
#>               z     a
#>           <num> <int>
#> 1:  0.183072670     1
#> 2:  0.009171455     0
#> 3: -1.154114228     0
#> 4:  0.792409843     1
#> 5: -1.012248393     1
#> 

# constant covariate
x <- base %join% list(data.frame(a = 0), data.frame(a = 1))
x(n)
#> $`0`
#>             z     a
#>         <num> <num>
#> 1: -1.6981482     0
#> 2:  0.5664903     0
#> 3: -0.2278301     0
#> 4:  1.0684798     0
#> 5:  0.9074631     0
#> 
#> $`1`
#>             z     a
#>         <num> <num>
#> 1: -0.5325431     1
#> 2:  0.1250143     1
#> 3:  0.5675025     1
#> 4:  0.4602246     1
#> 5:  0.7143456     1
#> 

# baseline covariate
x <- base %join% function(n) data.frame(w = rnorm(n))
x(n)
#> $`0`
#>             z          w
#>         <num>      <num>
#> 1: -4.2679169 -0.7987033
#> 2:  0.6736688  1.3327489
#> 3: -0.1643476  0.8529500
#> 4: -0.6817609  1.0937794
#> 5: -0.6319921 -0.8712126
#> 
#> $`1`
#>             z          w
#>         <num>      <num>
#> 1: -2.9004381 -0.7987033
#> 2: -1.5049406  1.3327489
#> 3: -1.3073107  0.8529500
#> 4: -0.6787600  1.0937794
#> 5: -0.8448241 -0.8712126
#>