堆叠结果

时间:2018-11-21 19:30:07

标签: r

我正在使用以下代码生成数据,并且正在估计一系列变量(covar1和covar2)的回归模型。我还为系数创建了置信区间,并将它们合并在一起。

我一直在这里和其他站点上研究各种示例,但是我似乎无法完成我想要的事情。我想将每个covar的结果堆叠到一个数据帧中,并通过可归因于其的covar标记每个结果簇(即“ covar1”和“ covar2”)。这是使用lapply生成数据和结果的代码:

##creating a fake dataset (N=1000, 500 at treated, 500 at control group)
#outcome variable
outcome <- c(rnorm(500, mean = 50, sd = 10),  rnorm(500, mean = 70, sd = 10))

#running variable
running.var <- seq(0, 1, by = .0001)
running.var <- sample(running.var, size = 1000, replace = T)

##Put negative values for the running variable in the control group
running.var[1:500] <- -running.var[1:500]

#treatment indicator (just a binary variable indicating treated and control groups)
treat.ind <- c(rep(0,500), rep(1,500))

#create covariates
set.seed(123)
covar1 <- c(rnorm(500, mean = 50, sd = 10), rnorm(500, mean = 50, sd = 20))
covar2 <- c(rnorm(500, mean = 10, sd = 20), rnorm(500, mean = 10, sd = 30))
data <- data.frame(cbind(outcome, running.var, treat.ind, covar1, covar2))
data$treat.ind <- as.factor(data$treat.ind)

#Bundle the covariates names together
covars <- c("covar1", "covar2")

#loop over them using a convenient feature of the "as.formula" function
models <- lapply(covars, function(x){
  regres <- lm(as.formula(paste(x," ~ running.var + treat.ind",sep = "")), data = d)
  ci <-confint(regres, level=0.95)
  regres_ci <- cbind(summary(regres)$coefficient, ci)
})
names(models) <- covars
print(models)

任何朝着正确方向移动的链接,或者链接到我刚遇到的帖子,都将受到极大的赞赏。

1 个答案:

答案 0 :(得分:1)

第二个参数是列表(like in here)时,您可以使用do.call

do.call(rbind, models)

我(可能)对您的lapply函数进行了改进。这样,您可以将估计的参数和变量保存在data.frame中:

models <- lapply(covars, function(x){
  regres <- lm(as.formula(paste(x," ~ running.var + treat.ind",sep = "")), data = data)
  ci <-confint(regres, level=0.95)
  regres_ci <- data.frame(covar=x,param=rownames(summary(regres)$coefficient),
                          summary(regres)$coefficient, ci)
})

do.call(rbind,models)