我有3个数据集,希望对所有数据运行相同的线性模型,存储系数及其置信上限和下限.

set.seed(1)
    school1 = data.frame(student = sample(c(1:100), 100, r = T),
                         score = runif(100))
    school2 = data.frame(student = sample(c(1:100), 100, r = T),
                         score = runif(100))
    school3 = data.frame(student = sample(c(1:100), 100, r = T),
                         score = runif(100))
                         
    schools = list('school1', 'school2', 'school3')
    storage <- vector('list', length(schools))
    
    for(i in seq_along(schools)){
      tmpdat <- schools[[i]]
      tmp <- lm(score ~ x1, data = tmpdat)
      storage[[i]] <- summary(tmp)$coef[1]
    }

我希望生成存储所有信息以及数据集名称的WANT:

WANT = data.frame(data = c('school1', 'school2', 'school3'),
                  coef = c(0,0,0),
                  coefLL = c(0,0,0),
                  coefUL=c(0,0,0))

但我在苦苦挣扎,我遍历了数据集,但不知道如何存储我需要的所有信息……还有,我有大约1000个数据集,所以最有效的方法是最好的,非常感谢

推荐答案

你的设置有一些奇怪的地方--你没有学校数据集的列表,你有学校名称的列表?说到"系数",你的意思是你只对斜率感兴趣(抛开截距?)为什么你的模型中有一个预测变量x1,而它不在你的数据中……

library(broom)
library(tidyverse)
schoolnames <- c('school1', 'school2', 'school3')
schools <- mget(schoolnames)
res <- vector(length = 3, mode = "list")
names(res) <- schoolnames
for(i in seq_along(schools)){
      tmp <- lm(score ~ student, data = schools[[i]])
      res[[i]] <- (tidy(tmp, conf.int = TRUE)
           |> filter(term == "student")
           |> select(estimate, conf.low, conf.high)
      )
    }
WANT <- bind_rows(res, .id = "school")

你也可以用purrr::map()来做这个...

如果出于某种原因,你想以一种低技术含量的方式做到这一点,你可以:

res <- data.frame(schools = schoolnames, est = rep(NA,3),
                  lwr = rep(NA,3), upr = rep(NA,3))
for(i in seq_along(schools)){
      tmp <- lm(score ~ student, data = schools[[i]])
      ## use element 2/row 2 to pick out the slope coefficient/CIs
      res[i,1] <- coef(tmp)[2]
      res[i,2] <- confint(tmp)[2,1]  ## lower CI in column 1
      res[i,3] <- confint(tmp)[2,2]
}

R相关问答推荐

如何修复R码的置换部分?

如何将旋转后的NetCDF转换回正常的纬度/经度网格,并使用R?

将数字转换为分钟和秒

使用R闪光显示所有数据点作为默认设置

在数组索引上复制矩阵时出错

在使用bslb和bootstrap5时,有没有办法更改特定dt行的 colored颜色 ?

R Read.table函数无法对制表符分隔的数据正常工作

悬崖三角洲超大型群数计算导致整数溢出

在多页PDF中以特定布局排列的绘图列表不起作用

R中Gamma回归模型均方误差的两种计算方法不一致

如何在R中使用hmm TMB提前一步预测观察到的状态?

R中治疗序列的相对时间指数

如何更改包中函数中的参数?

排序R矩阵的行和列

GOGPLATE geom_boxploy色彩疯狂

有没有办法将勾选/审查标记添加到R中的累积关联图中?

希望解析和复制R中特定模式的数据

如何计算多个变量的百分比与总和的百分比?

如何在一种 colored颜色 中设置数值变量的 colored颜色 和高于阈值的 colored颜色 点?

GgHighlight找不到它创建的列:`Highlight..1`->;`Highlight.....`