R/get_coef.R

Defines functions get_coef

Documented in get_coef

#' A function that extracts coefficients.
#'
#' A function that extracts coefficients from mediation and outcome model.
#' @param res_SMAHP Outputs from SMAHP
#' @return A data frame which includes the name of exposure and mediator with coefficients from mediation and outcome model.
#'   \item{beta1}{The coefficient estimate of exposure in mediation model}
#'   \item{beta2}{The coefficient estimate of mediator in outcome model}
#'   \item{beta3}{The coefficient estimate of exposure in outcome model}
#' @import data.table
#' @export
#' @examples
#' \donttest{
#' data(example_dat)
#' surv_dat <- example_dat$surv_dat
#' res_SMAHP <- SMAHP(example_dat$X, example_dat$M, example_dat$C, time = surv_dat$time,
#' status = surv_dat$status)
#' get_coef(res_SMAHP)
#' }

get_coef <- function(res_SMAHP){
  m <- res_SMAHP$p_med_matrix
  pos <- which(m == 1, arr.ind = TRUE)
  if(nrow(pos) == 0){
    return(message("No mediation effect detected!"))
  } else {
    tab <- list()
    med_results <- res_SMAHP$med_results
    outcome_model <- res_SMAHP$outcome_model
    for(i in 1:nrow(pos)){
      x_name <- rownames(m)[pos[i,1]]
      m_name <- colnames(m)[pos[i,2]]
      beta1 <- as.numeric(med_results[[m_name]][x_name])
      beta2 <- as.numeric(outcome_model[paste0("M_", m_name)])
      beta3 <- as.numeric(outcome_model[paste0("X_", x_name)])
      tab[[i]] <- data.frame(X = x_name, M = m_name, beta1 = beta1, beta2 = beta2, beta3 = beta3)
    }
    final_tab <- rbindlist(tab)
    return(final_tab)
  }
}

Try the SMAHP package in your browser

Any scripts or data that you put into this service are public.

SMAHP documentation built on April 4, 2025, 1:36 a.m.