R/as.rv.stanfit.R

#' Convert simulations generated by Stan to a list of rv objects
#' 
#' Convert simulations generated by Stan to a list of rv objects.
#' 
#' 
#' @param x A 'stanfit' object
#' @param list. logical; return a list of \code{rv} objects instead of a single
#' \code{rv} object (vector)?
#' @param \dots (ignored)
#' @return A list of rv objects, with the names set for each rv object.
#' @author J Kerman
#' @references Stan: \url{https://mc-stan.org/}
#' @keywords manip
#' 
#' @export
#' @method as.rv stanfit
as.rv.stanfit <- function (x, list.=TRUE, ...) {
  f <- get("extract", mode="function")
  L <- lapply(f(x), rvsims)
  P <- x@par_dims
  for (name in names(L)) {
    x <- L[[name]]
    n <- P[[name]]
    if (length(n) == 0) {
      names(x) <- name
    } else if (length(n) == 1) {
      names(x) <- paste(name, "[", 1:n, "]", sep="")
    } else {
      C <- lapply(n, function (k) 1:k)
      A <- as.list(do.call(expand.grid, C))
      A$sep <- ","
      indices <- do.call(paste, A)
      names(x) <- paste(name, "[", indices, "]", sep="")
    }
    L[[name]] <- x
  }
  if (! list.) {
    L <- do.call(c.rv, L)
  }
  return(L)
}
jsta/rv documentation built on Feb. 12, 2022, 5:13 p.m.