R/add_stancode.R

Defines functions add_stancode

Documented in add_stancode

#' Add Stan code to the generated quantities block
#'
#' @param scode_raw Stan code generated by `brms::make_stancode()`.
#' @param new_code A character string containing Stan code to add to the generated quantities block
#' @param block Specify the code block to modify.
#'
#' @return  A Stan program of class `brmsmodel`.
#' @importFrom stringr str_replace
#' @export
#'
#' @examples
#' library("brms")
#' data <- read.csv(paste0(system.file("extdata", package = "bgamcar1"), "/data_car1.csv"))
#' scode <- make_stancode(bf(y ~ ar(time = x)), data)
#' add_stancode(scode, "\n  // add new code here:", block = "generated quantities")
add_stancode <- function(scode_raw, new_code, block) {
  scode <- str_replace(
    scode_raw,
    paste0("(", block," \\{\n(.|\n)*?)(?=\n\\})"),
    paste(c("\\1\n  ", new_code), collapse = "")
  )
  class(scode) <- "brmsmodel"
  scode
}
bentrueman/bgamcar1 documentation built on July 6, 2024, 11:16 p.m.