亲爱的 Stackoverflow 社区
我正在 R 中进行一项研究,我正在对不同的依赖项进行几个二项式逻辑回归。这些分析是反复进行的,只是进行了微小的更改,我正在与我的同事分享结果,最好是在漂亮的表格中,而不是凌乱的 R 结果。如果我只打算这样做几次,我可以将所有分析作为单一回归进行,然后使用 sjt.glm 制作漂亮的表格。尽管我一遍又一遍地进行这些类似的分析,但我正在使用 lapply 循环来加速和简化该过程。不幸的是,我无法让 lapply 和 sjt.glm 合作。理想情况下,我会从 lapply 循环中获取结果,并使用 sjt.glm 制作一个漂亮的水平对齐表。
请参阅示例(对于丑陋的编码感到抱歉)
library(sjPlot)
swiss$y1 <- ifelse(swiss$Fertility < median(swiss$Fertility), 0, 1)
swiss$y2 <- ifelse(swiss$Infant.Mortality < median(swiss$Infant.Mortality), 0, 1)
swiss$y3 <- ifelse(swiss$Agriculture < median(swiss$Agriculture), 0, 1)
#Normal slow way would be
fitOR1 <- glm(y1 ~ Education + Examination + Catholic, data = swiss,
family = binomial(link = "logit"))
fitOR2 <- glm(y2 ~ Education + Examination + Catholic, data = swiss,
family = binomial(link = "logit"))
fitOR3 <- glm(y3 ~ Education + Examination + Catholic, data = swiss,
family = binomial(link = "logit"))
#and then simply use summary and other formulas to look at the results
summary(fitOR1);exp(cbind(OR = coef(fitOR1), confint(fitOR1)))
#but with 20+ dependents, this would become tedious
#Doing the same analysis as a laply loop, is relatively easy (and non-tedious)
varlist <- names(swiss[c(7:9)])
results <- lapply(varlist, function(x){
glm(substitute(i ~ Education + Examination + Catholic, list(i=as.name(x))),
family =binomial, data = swiss)})
for (i in 1:3) print(summary(results[[i]]))
for (i in 1:3) print(exp(cbind(OR = coef(results[[i]]), confint(results[[i]]))))
#Though here is the catch. To get the output/results into a nice table
#I can easily use sjt.glm for the "standard" single logistic regressions.
sjt.glm(fitOR1,fitOR2,fitOR3, file = "SwissFits.html")
#Though I can't think of how I could do this for the loop-results.
#The closest I have come is perhaps something like
for(i in 1:3)(sjt.glm(results[[i]],file="LoopSwissFits.html"))
#but then I only get the results from the last regression.
#One alternative is to do
lapply(varlist,function(x){ sjt.glm(
glm(substitute(i ~ Education + Examination + Catholic, list(i=as.name(x))),
family =binomial, data = swiss), file = paste0("SwissFits_",(i=as.name(x)),".html"))})
#but then I get three separate files, when it would be preferable to
#have the results in one horizontally oriented file
你们中有人对我的问题有简洁优雅的解决方案吗?
非常感谢您!