我正在创建一个带有结果,协变量和曝光的lm循环函数。 此循环创建lm输出,然后将其放入空数据帧。但是,当我调用函数时,将空数据框的创建放入函数中时,不会创建数据框。当我将数据框的创建放在函数外部并运行它时,它只会创建一个未填充的空数据框。我想知道解决此问题的最佳方法是什么。下面是我的代码:
outcomes<- c(out1,out2,out3)
exposure <-c(exp1,exp2,exp3)
my_covariates <- c(cov1,cov2,cov3)
reg_func <- function(data = ads, exposure, my_covariates, outcomes)
{
#creates empty dataframe
myreg_data <- data.frame()
for (i in seq_along(outcomes))
{
for (j in seq_along(exposure))
{
mylm <- lm(formula(paste(outcomes[i], " ~ ", paste(my_covariates,
collapse = " + "), " + " ,paste(exposure[j]))), data = ads)
ctable<-as.data.frame(coef(summary(mylm)))
ctable
dsa<-as.data.frame(cbind(ctable,Variable = rownames(ctable),
Outcome = outcomes[i],
Exposure = exposure[j],
Model="Cont.LR",
Model_n = paste(length(mylm$residuals))))
names(dsa)[4] <- "Pvalue"
rownames(dsa)<-NULL
myreg_data <- rbind(myreg_data,dsa)
return(myreg_data)
}}}
reg_func(data = ads, exposure = exposure, my_covariates =
my_covariates, outcomes = outcomes)