R/compute_coefficients.R

Defines functions compute_coefficients

Documented in compute_coefficients

#' Compute the simple coefficients for several models
#' @param specifications  Tibble. Table containing the specifications of the models to run. Moderating variables should be the interacting variables separated by ".x.", starting with the variable of interest, finishing with the moderating variable.
#' @return A tibble gwith all the coefficients associating each dependent, independent, and moderating variables.
#' @seealso estimate
#' @importFrom tibble tibble
#' @importFrom tibble is_tibble
#' @importFrom tidyr nest
#' @importFrom tidyr unnest
#' @importFrom tidyr replace_na
#' @importFrom tidyr spread
#' @importFrom tidyr gather
#' @importFrom tidyr separate
#' @importFrom dplyr %>%
#' @importFrom dplyr group_by
#' @importFrom dplyr mutate
#' @importFrom dplyr select
#' @importFrom purrr pmap
#' @importFrom purrr map
#' @importFrom stringr str_replace_all
#' @export



compute_coefficients <- function(specifications){
  
  stopifnot(
    tibble::is_tibble(specifications),
    names(specifications) == c("sample","formula","method","family","md_imputation","md_method","draws","size","cores")
  )
  
  # Bind variables
  model <- NULL
  independent <- NULL
  pval <- NULL
  error <- NULL
  moderator <- NULL
  coefficient <- NULL
  moderation <- NULL
  base <- NULL
  dependent <- NULL
  draw <- NULL
  data <- NULL
  relation <- NULL
  path <- NULL
  
  
  specifications$model <- purrr::pmap(
    specifications,
    modestim::estimate
  ) 
  
  estimation <- specifications %>%
    dplyr::select(model) %>%
    tidyr::unnest() %>%
    dplyr::mutate(independent = stringr::str_replace_all(independent, '\\(Intercept\\)','constant')) %>%
    tidyr::separate(independent, into = c("independent","moderator"), sep = ".x.", fill = "right") %>%
    dplyr::select(-error, -pval) %>%
    tidyr::replace_na(list(moderator = "base"))
  
  prep_path <- function(x){
    x %>%
      tidyr::spread(moderator, coefficient) %>%
      tidyr::gather(moderator, moderation, -base)
  }
  
  estimation <- estimation %>%
    dplyr::group_by(dependent, independent, draw) %>%
    tidyr::nest() %>%
    dplyr::mutate(data = purrr::map(data, prep_path)) %>%
    tidyr::unnest() %>%
    tidyr::replace_na(list(moderator = "base", moderation = 0)) %>%
    dplyr::mutate(
      path = paste(independent, dependent, sep = "_"),
      relation = "direct"
    ) %>%
    dplyr::select(relation, path, dependent, independent, moderator, draw, base, moderation)
  
  return(estimation)
}
NicolasJBM/modestim documentation built on Aug. 26, 2019, 5:29 a.m.