Skip to content

Instantly share code, notes, and snippets.

@jsilve24
Created July 10, 2018 14:28
Show Gist options
  • Save jsilve24/f9c6679e5883d6454ef75c7550a10fcc to your computer and use it in GitHub Desktop.
Save jsilve24/f9c6679e5883d6454ef75c7550a10fcc to your computer and use it in GitHub Desktop.
Takes output from Stan Optimizing and cleans it to more standard form.
#' Clean Output of Stan Optimizing Samples
#'
#' @param optimfit result of call to rstan::optimizing
#' @param pars optional character vector of parameters to include
#'
#' @return list of arrays
#' @importFrom stringr str_count
#' @importFrom rlang syms
#' @importFrom dplyr matches select mutate
#' @importFrom tidyr gather separate
#' @importFrom purrr map map2
#' @importFrom driver spread_array
#' @export
clean_optimizing <- function(draws, pars=NULL){
cl <- draws %>%
as.data.frame()
if (!is.null(pars)) cl <- select(cl, dplyr::matches(paste0("^(",paste(pars, collapse = "|"), ")\\["), ignore.case=FALSE))
cl <- cl %>%
mutate(dim_1 = 1:n()) %>%
gather(par, val, -dim_1) %>%
separate(par, c("parameter", "dimensions"), sep="\\[|\\]", extra="drop") %>%
split(., .$parameter)
dn <- map(cl, ~str_count(.x$dimensions[1], "\\,")+1) %>%
map(~paste0("dim", 1:.x))
cl <- cl %>%
map2(dn, ~separate(.x, dimensions, .y, "\\,", convert=TRUE)) %>%
map(~dplyr::select(.x, -parameter)) %>%
map2(dn, ~spread_array(.x, val, !!!rlang::syms(c("dim_1", .y))))
return(cl)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment