【问题标题】:Loop regression: creating interaction term, storing results, pulling out only significant ones循环回归:创建交互项,存储结果,只提取有意义的项
【发布时间】:2019-02-15 09:53:27
【问题描述】:

我有一个数据集

auto <- read.csv("http://www-bcf.usc.edu/~gareth/ISL/Auto.csv")

我试图在其中寻找任何重要的交互术语。我想要只包含单个交互及其构成项的回归(即圆柱体 + 加速度 + 圆柱体:加速度是我要检查的一种回归)。

到目前为止,使用其他 Stackoverflow 问题,我已经能够想出这个:

results <- NULL
vars=colnames(auto)[-c(1,9)]
for(i in vars){
for(j in vars){
if(i ! = j){
factor=paste(i,j,sep='*')}
for(k in 1:20){
results[[k]]<-summary(lm(paste("mpg~", factor), data=auto)))
}}}

但是,这会不断生成一个列表,其中仅存储最后一次交互(即起源*年份的系数)。如果代码不仅具有唯一值,而且还具有术语的平方版本,我也可以。但是,由于其中两个(列表中的最后两个,原产地和年份)不值得平方,并且由于我不知道如何为 i 和 j 设置不同的长度并使其起作用,因此我将其省略了.

我应该怎么做才能从这个循环中得到我想要的结果?我应该以不同的方式去做吗?我还尝试创建所有交互,然后将其附加到数据框并通过它运行一个循环,但它似乎没有任何效率/可能。

【问题讨论】:

    标签: r loops regression interaction


    【解决方案1】:

    您的k 循环除了将结果存储到长度为 20 的列表中之外没有其他效果。所有值都将相同,剩下的就是i*j 的最后一个组合的摘要。我会预先计算组合,为每个组合创建一个列表并将其提供给单个循环。

    请注意,R 已经附带了一个 mtcars 数据集。

    vars <- colnames(mtcars)[-1]
    
    # Prepare combinations of variables.
    combos <- combn(vars, 2, simplify = FALSE)
    combos <- sapply(combos, FUN = paste, collapse = "*")
    
    # For each combination, create a formula object and use it in the regression.
    # It would be prudent to include the data object into function argument.
    results <- lapply(combos, FUN = function(x) {
      frm <- as.formula(paste("mpg ~ ", x))
      summary(lm(frm, data = mtcars))
    })
    
    # Rename results names for pretty purposes.
    names(results) <- combos
    
    > results[1]
    $`cyl*disp`
    
    Call:
    lm(formula = frm, data = mtcars)
    
    Residuals:
        Min      1Q  Median      3Q     Max 
    -4.0809 -1.6054 -0.2948  1.0546  5.7981 
    
    Coefficients:
                 Estimate Std. Error t value Pr(>|t|)    
    (Intercept) 49.037212   5.004636   9.798 1.51e-10 ***
    cyl         -3.405244   0.840189  -4.053 0.000365 ***
    disp        -0.145526   0.040002  -3.638 0.001099 ** 
    cyl:disp     0.015854   0.004948   3.204 0.003369 ** 
    ---
    Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
    
    Residual standard error: 2.66 on 28 degrees of freedom
    Multiple R-squared:  0.8241,    Adjusted R-squared:  0.8052 
    F-statistic: 43.72 on 3 and 28 DF,  p-value: 1.078e-10
    

    【讨论】:

    • 这正是我所需要的!非常感谢。我还在最后添加了这个以打印我分配任务所需的结果,这需要识别重要的交互项:names(results) &lt;- combos for(i in combos){ ifelse(results[[i]][["coefficients"]][16]&lt;=.05,print(paste(i, "is a significant interaction")),print(paste(i, "is not a significant interaction"))) } 只是一个问题:如果我放置对象结果,我的循环会更好地工作吗在循环之外并将循环输出分配给它,就像你对 lapply 所做的那样?
    • @BenWest 您的循环最后一部分存在根本缺陷。另外,我猜你可能必须定义“更好”。
    猜你喜欢
    • 2018-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-29
    • 1970-01-01
    • 2018-12-03
    • 1970-01-01
    相关资源
    最近更新 更多