Created
August 29, 2024 03:02
-
-
Save sientifiko/db35db74e143986854a4152ab90d9979 to your computer and use it in GitHub Desktop.
Función que genera un output similar al de stargazer, pero en formato tabulado para que puedan exportarlo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
generate_regression_table <- function(models, se_type = "HC3") { | |
require(sandwich) | |
require(lmtest) | |
# Initialize lists to store results | |
results_list <- list() | |
# Loop over each model | |
for (i in seq_along(models)) { | |
model <- models[[i]] | |
# Calculate robust standard errors | |
robust_se <- sqrt(diag(vcovHC(model, type = se_type))) | |
# Extract model statistics | |
coefficients <- coef(model) | |
std_errors <- robust_se | |
t_values <- coefficients / std_errors | |
p_values <- 2 * pt(-abs(t_values), df = df.residual(model)) | |
# Extract additional model statistics | |
n_obs <- length(model$residuals) | |
r_squared <- summary(model)$r.squared | |
adj_r_squared <- summary(model)$adj.r.squared | |
residual_std_error <- summary(model)$sigma | |
f_statistic <- summary(model)$fstatistic[1] | |
# Create a data frame for the coefficients and standard errors | |
model_df <- data.frame( | |
Term = names(coefficients), | |
Coefficient = paste0(round(coefficients, 4), " (", round(std_errors, 4), ")") | |
) | |
# Add other statistics to the model data frame | |
model_df <- rbind( | |
model_df, | |
data.frame(Term = "N", Coefficient = n_obs), | |
data.frame(Term = "R^2", Coefficient = round(r_squared, 4)), | |
data.frame(Term = "Adj. R^2", Coefficient = round(adj_r_squared, 4)), | |
data.frame(Term = "Residual Std. Error", Coefficient = round(residual_std_error, 4)), | |
data.frame(Term = "F Statistic", Coefficient = round(f_statistic, 4)) | |
) | |
# Store the model results in the list | |
results_list[[paste("Model", i)]] <- model_df$Coefficient | |
} | |
# Combine all models' results into a single data frame | |
final_results <- data.frame( | |
Term = model_df$Term, | |
do.call(cbind, results_list) | |
) | |
# Return the final results as a data frame | |
return(final_results) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment