Skip to contents

Create a model factory function from a template object

Usage

model_from_template(
  template,
  use_defaults = FALSE,
  use_length = FALSE,
  optional = FALSE
)

Arguments

template

A template list to derive model from.

use_defaults

Whether to use template values as default values.

use_length

not used at the moment

optional

Logical whether all or no variable is optional. Alternative a vector of names of values that are optional.

Value

A model factory function.

Examples

template <- list(
  a = 10L,
  b = 10L
)


my_model <- model_from_template(template)
# Succeeds
my_model(a = c(1:10), b = 7L)
#> $a
#>  [1]  1  2  3  4  5  6  7  8  9 10
#> 
#> $b
#> [1] 7
#> 

# Fails
try(my_model(10, 8))
#> Error in obj[[name]] : subscript out of bounds


# Set values to optional
my_model <- model_from_template(template, optional = TRUE)
my_model(a = 12L) # returns NA for b
#> $a
#> [1] 12
#> 
#> $b
#> [1] NA
#> 

# When optional is set to FALSE the model throws an error
my_model <- model_from_template(template, optional = FALSE)
try(my_model(a = 12L)) # returns NA for b
#> Error in my_model(a = 12L) : Type check(s) failed
#> ---
#> Type check failed for 'b'
#> value:  logi NA
#> type: logical
#> class: logical
#> length: 1
#> expected: {
#>     typeof(x) == "integer" & class(x) == "integer" & mode(x) == 
#>         "numeric"
#> }


# Use defaults if none provided
my_model <- model_from_template(template, use_defaults = TRUE, optional = FALSE)
my_model(a = 12L)
#> $a
#> [1] 12
#> 
#> $b
#> [1] 10
#>