R/data-block.R

Defines functions get_nobs has_length data_block

Documented in data_block

#' Create Data Block from Data List
#'
#' Automate writing the STAN data block from your data.
#'
#' @param x A nlist
#'
#' @return A string
#' @export
#'
#' @examples
#' mod_data <- nlist::as_nlist(list(
#'   X = c(1L, 2L, 3L, 4L),
#'   Y = c(1.2, 7.3, 8.9, 2.6),
#'   nObs = 4L
#' ))
#' data_block(mod_data)
data_block <- function(x) {
  nlist::chk_nlist(x)
  nobs <- get_nobs(x)
  x <- purrr::keep(x, has_length)
  strings <- purrr::imap_chr(x, .f = data_block_element, nobs = nobs)
  if (length(strings)) {
    strings <- paste0("  ", strings, ";\n", collapse = "")
  }
  paste0("data {\n", strings, "}", collapse = "")
}

has_length <- function(x) {
  length(x) != 0
}

get_nobs <- function(x) {
  nobs <- x$nObs
  if (rlang::is_scalar_integer(nobs)) {
    return(nobs)
  }
  0L
}
poissonconsulting/smbr documentation built on Sept. 24, 2024, 8:47 p.m.