R/vcov_env.R

Defines functions get_vcov

Documented in get_vcov

#' @title Get the variance-covariance matrix of a gamlss object in any environment
#'
#' @description
#' The \code{vcov.gamlss} method relies on the object passed to the \code{data}
#' parameter of the call to \code{gamlss::gamlss} to be found in the global environment.
#' However, this may well not be the case, especially if the object were fit inside a function.
#' The object may also exist but have changed its value.
#'
#' It would be ideal to simply pass the dataframe to \code{vcov.gamlss} directly,
#' but that would need to adjust the gamlss package (as I don't know how to create
#' the same package but with a different name and this slight adjustment), which I
#' would rather avoid.
#'
#' So, this function assigns the dataframe to the global environment with the name
#' that was passed to \code{mod}.
#'
#' @param mod gamlss object. Object of class gamlss.
#' @param data dataframe. Dataframe originally passed to \code{data} parameter in
#' \code{gamlss} function used to fit \code{mod}.
#' @param data_name character. Name of object passed to \code{data} parameter in
#' \code{gamlss} function used to fit \code{mod}.
#'
#' @details
#' It's unclear what would happen under parallel processing or if the user
#' were altering this object in the global environment as well.
#'
#' @return Variance-covariance matrix as output by \code{vcov.gamlss}.
#'
#' @export
#'
#' @examples
#'
#' data_test <- data.frame(x = runif(10))
#' data_test[['y']] <- 3 * data_test[['x']] + rnorm(10, sd = 1)
#' mod_gam <- gamlss::gamlss(y ~ x, data = data_test)
# vcov_env(mod = mod_gam, data = data_test, data_name = 'data_test')
get_vcov <- function(mod, data, data_name){
  # change object with name data_name in .GlobalEnv to
  # original value, if it exists
  if(exists(data_name, .GlobalEnv)){
    data_name_global <- get(data_name, envir = .GlobalEnv)
    on.exit(assign(data_name, data_name_global, envir = .GlobalEnv))
  }
  assign(data_name, data, envir = .GlobalEnv)
  vcov(mod)
}
MiguelRodo/gamlssutils documentation built on July 9, 2020, 12:48 a.m.