Skip to contents

Create a collection of constraint variables

Usage

new_variable_collection(name = "", explicit = TRUE, r6_def = NULL)

Arguments

name

collection name, default is empty

explicit

whether setting and getting variables should be explicit, default is TRUE, which means trying to get undefined variables will result in errors

r6_def

R6 class generator; default is RAVEVariableCollection. This input is for class definitions that are child classes of RAVEVariableCollection.

Value

A RAVEVariableCollectionWrapper instance

Examples


collection <- new_variable_collection()

# Add unconstrained variables
collection$add_variable(id = "title", "Voltage traces")

# Add a variable with placeholder
collection$add_variable(id = "time_points")

# Add variable with constraints
collection$add_variable(
  id = "analysis_range",
  var = new_constrained_variable(
    name = "Analysis range",
    initial_value = c(0, 1),
    constraints = "numeric",
    any.missing = FALSE,
    len = 2,
    sorted = TRUE,
    null.ok = FALSE
  )
)

collection$use_constraints(quote({
  # `x` is the list of values
  time_range <- range(.x$time_points, na.rm = TRUE)
  if(
    .x$analysis_range[[1]] >= time_range[[1]] &&
    .x$analysis_range[[2]] <= time_range[[2]]
  ) {
    # valid
    re <- TRUE
  } else {

    # error message
    re <- sprintf(
      "Invalid analysis range, must be within [%.2f, %.2f]",
      time_range[[1]], time_range[[2]]
    )
  }

  re
}))


collection$set_value("time_points", seq(-1, 10, by = 0.5))

# validation will pass
collection$validate()
#> [1] TRUE

# Get variable values
collection$as_list()
#> $analysis_range
#> [1] 0 1
#> 
#> $time_points
#>  [1] -1.0 -0.5  0.0  0.5  1.0  1.5  2.0  2.5  3.0  3.5  4.0  4.5  5.0  5.5  6.0
#> [16]  6.5  7.0  7.5  8.0  8.5  9.0  9.5 10.0
#> 
#> $title
#> [1] "Voltage traces"
#> 
collection[]
#> $analysis_range
#> [1] 0 1
#> 
#> $time_points
#>  [1] -1.0 -0.5  0.0  0.5  1.0  1.5  2.0  2.5  3.0  3.5  4.0  4.5  5.0  5.5  6.0
#> [16]  6.5  7.0  7.5  8.0  8.5  9.0  9.5 10.0
#> 
#> $title
#> [1] "Voltage traces"
#> 

# get one variable
collection$get_value("analysis_range")
#> [1] 0 1

# get unregistered variable
collection$get_value("unregistered_variable")
#> NULL

# get partial variables with single `[`
collection["title", "analysis_range"]
#> $title
#> [1] "Voltage traces"
#> 
#> $analysis_range
#> [1] 0 1
#> 
collection[c("title", "analysis_range")]
#> $title
#> [1] "Voltage traces"
#> 
#> $analysis_range
#> [1] 0 1
#> 

collection$set_value("analysis_range", c(-2, 5))

if (FALSE) { # \dontrun{
collection$validate()

# error out when explicit, please either
# set explicit=TRUE or register the variable via $add_variable
collection$set_value("unregistered_variable", 1)

} # }

# turn off explicit variable option
collection$explicit <- FALSE
collection$set_value("unregistered_variable", 1)
collection$get_value("unregistered_variable")
#> [1] 1