I have a loop in my code that pulls summary statistics from each logistic regression I perform on each dataset. I would like it to also show the count of each level for each variable if possible. I am pretty new to loops though, and am not quite sure how to ask R how to do it.
Here is an example of the code I am currently using. The data I am using is different but the rest of the analysis is nearly the same.
library(tidyverse)
install.packages("AER")
library("AER")
data(Affairs, package="AER")
Affairs$ynaffair[Affairs$affairs > 0] <- 1
Affairs$ynaffair[Affairs$affairs == 0] <- 0
Affairs <- Affairs %>%
mutate_at(c("affairs", "religiousness", "occupation", "rating", "ynaffair"), as.factor)
frmlas <- list(ynaffair~gender,
ynaffair~children,
ynaffair~religiousness,
ynaffair~occupation,
ynaffair~rating)
output <- list()
output_df_list <- list()
for(i in 1:length(frmlas)){
output[[i]] <- glm(frmlas[[i]], data = Affairs, family=binomial)
names(output)[i] <- capture.output(frmlas[[i]])
output_df_list[[i]] <- data.frame("Model"=capture.output(frmlas[[i]]),
"Covariate"=names(output[[i]]$coefficients),
"Beta_Estimate"=output[[i]]$coefficients,
"P_val"=summary(output[[i]])$coefficients[,4],
"CI_95_LL"=confint(output[[i]])[,1],
"CI_95_UL"=confint.default(output[[i]])[,2])
rownames(output_df_list[[i]]) <- NULL
}
output_df_full_t1 <- do.call("rbind", output_df_list)
output_df_full_t1 <- output_df_full_t1 %>%
mutate(OR = exp(Beta_Estimate)) %>%
mutate(CI_95_LL = exp(CI_95_LL),
CI_95_UL = exp(CI_95_UL)) %>%
select(Model, Covariate, OR, CI_95_LL, CI_95_UL, P_val) %>%
filter(!(Covariate %in% '(Intercept)')) %>%
mutate_if(is.numeric, round, digits = 3) %>%
unite(CI, c(CI_95_LL, CI_95_UL), sep = ", ", remove = TRUE)
head(output_df_full_t1)
Output snip
This is where I found this piece of code, and then modified it slightly:
https://bookdown.org/kdonovan125/ibis_data_analysis_r4/intro-7.html
The expected result would be a new column with the counts of each level in the output. Or if that isn’t possible, and you have an alternative suggestion, I would be grateful for the advice. My mentor/boss just doesn’t want me copy/ pasting the counts for each one. The end goal is to output the result to an excel file.
Desired final output
I need to do this many times, so figuring this out would be very time-saving for me.
Thanks!
Newtostats_24 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.