How to put SE values under coefficient estimates?

46 Views Asked by At

I want to have the estimated value of the coefficient and SE values in one cell. SE values should be under the coefficient values. To find out how to do it with the names of columns was easy but with the actual values, I have no idea. Does somebody know? Thanks.

The code below is the full table.

coefficients <- coef(selected_model)
std_errors <- summary(selected_model)$coefficients[, "Std. Error"]
p_values <- summary(selected_model)$coefficients[, "Pr(>|t|)"]

summary_data <- data.frame(
  Variable = c("(Intercept)", names(coefficients)[-1]), 
  Coefficient = round(coefficients, 6),
  Std_Error = c(std_errors[1], std_errors[-1]), 
  P_Value = p_values
)


add_stars <- function(p_value) {
  if (p_value < 0.001) {
    stars <- "***"
  } else if (p_value < 0.01) {
    stars <- "**"
  } else if (p_value < 0.05) {
    stars <- "*"
  } else if (p_value < 0.1) {
    stars <- "."
  } else {
    stars <- " "
  }
  return(stars)
}


summary_data$P_Value <- sapply(summary_data$P_Value, function(p_value) {
  stars <- add_stars(p_value)
  if (stars != "") {
    return(paste0(sprintf("%.4f", p_value), " ", stars))
  } else {
    return("")
  }
})

summary_data$Std_Error <- sprintf("(%.4f)", summary_data$Std_Error)

summary_table <- summary_data %>%
  gt() %>%
  cols_label(
    Variable = "Variable",
    # Coefficient = "Coefficient <br>(Std. Error)",
    Coefficient = "Coefficient",
    Std_Error = "(Std. Error)",
    P_Value = "P-Value",
    .fn = md
  ) %>%
  
  tab_header(
    title = "Stepwise Selection Model",
  )

summary_table

Table now

And I want to have Std.Error values below Coefficient in the same row.

0

There are 0 best solutions below