【问题标题】:Select and run regression on all unique pairs of variables对所有唯一的变量对选择并运行回归
【发布时间】:2015-04-02 18:41:00
【问题描述】:

假设我有以下数据:

set.seed(1)
n=1000
x1=rnorm(n,0,1)
x2=rnorm(n,0,1)
x3=rnorm(n,0,1)
d=cbind(x1,x2,x3)

如何对所有变量组合运行单变量回归,然后提取每个组合的斜率和 SE 的估计值?

这意味着我需要运行:

summary(lm(x1~x2,data=d)) # slope .0018; se .033
summary(lm(x1~x3,data=d)) # slope -.094; se .033
summary(lm(x2~x1,data=d)) # slope .002; se .03
...etc

最终,我想要如下所示的输出:

#slopes
      x1   x2     x3
  x1   NA .001  -.094
  x2  ...etc
  x3

 #se
      x1   x2     x3
  x1   NA .033  -.033
  x2  ...etc
  x3

【问题讨论】:

  • 如果您搜索pairssplom 并结合lm,您可能会找到工作示例。这些是用于显示数据和此类发现的图形表示的基本和 Lattice 图形函数。

标签: r lapply


【解决方案1】:

我借用了@DMC 的部分代码,但使用了combn 而不是嵌套循环。如果变量的数量很大,它可能会更有效,因为它只适合每个案例一次。

nvars <- ncol(d)
slopes <- matrix(NA, nrow = nvars, ncol = nvars)
se <- matrix(NA, nrow = nvars, ncol = nvars)

combs <- combn(nvars, 2) #Possible combinations

for (i in 1:ncol(combs)) {
  fit <- summary(lm(d[,combs[1,i]] ~ d[,combs[2,i]]))
  slopes[combs[1,i],combs[2,i]] <- slopes[combs[2,i],combs[1,i]] <- fit$coef[2,1]
  se[combs[1,i],combs[2,i]] <- se[combs[2,i],combs[1,i]] <- fit$coef[2,2]
}
colnames(se) <- rownames(se) <- colnames(slopes) <- rownames(slopes) <- colnames(d)

【讨论】:

    【解决方案2】:

    这是一种使用双循环的蛮力方法:

    # initialize matrices to store results
    slope <- matrix(NA, nrow = ncol(d), ncol = ncol(d))
    se <- matrix(NA, nrow = ncol(d), ncol = ncol(d))
    
    for (i in 1:ncol(d)){
    
      for(j in 1:ncol(d)){
    
        if (i == j) next
    
        m <- lm(d[,j] ~ d[,i])
        slope[i,j] <- unname(coef(m)[2])
        se[i,j] <- summary(m)$coef[2, 2]
    
    
      }
    
    }
    
    colnames(slope) <- paste("outcome:", 1:ncol(d))
    row.names(slope) <- paste("predictor:", 1:ncol(d))
    
    colnames(se) <- colnames(slope)
    row.names(se) <- row.names(slope)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-11
      • 1970-01-01
      • 1970-01-01
      • 2018-09-11
      • 2020-09-22
      • 2017-06-18
      • 1970-01-01
      • 2022-11-04
      相关资源
      最近更新 更多