【问题标题】:Comparing Coefficients from Two Different Linear Models in R比较 R 中两个不同线性模型的系数
【发布时间】:2017-11-30 04:54:19
【问题描述】:

我目前正在使用一种变量选择技术,该技术要求我确定任何给定变量的系数在具有不同变量组合的模型之间是否变化超过 20%。我试过了:

abs(model1$coefficients - model2$coefficients)/model1$coefficients

但是向量的长度不同(因为每个模型中的变量不同),所以它们没有正确排列。有没有办法在模型之间比较具有相同变量名称的系数?我可以手动完成,但有 50 多个系数和 10 个模型,所以需要很长时间。

对不起,如果这很明显,但我无法弄清楚。我环顾四周寻找答案,为我指明正确的方向,但所有这些都与系数的统计比较有关,并且不包含帮助我解决此问题的代码。

【问题讨论】:

    标签: r modeling


    【解决方案1】:

    您没有提供任何示例数据,所以我将基于模型y = a + b * x1 + c * x2 + e 模拟数据,其中e ~ N(0, 1)。

    然后我拟合两个模型:y ~ x1 和 y ~ x1 + x2,并使用自定义函数 getEstimates 从两个模型中提取相同预测变量的参数。使用 ANOVA 评估其他预测变量的重要性也是一个好主意。

    # Simulate some data
    set.seed(2017);
    generateData <- function(a = 1, b = 2, c = -2, nPoints = 1000) {
        x1 <- runif(nPoints);
        x2 <- runif(nPoints);
        y <- a + b * x1 + c * x2 + rnorm(nPoints);
        return(data.frame(y = y, x1 = x1, x2 = x2));
    }
    df <- generateData();
    
    
    # Fit1: y ~ a + b * x1
    fit1 <- lm(y ~ x1, data = df);
    
    # Fit2: y ~ a + b * x1 + c * x2
    fit2 <- lm(y ~ x1 + x2, data = df);
    
    # ANOVA to explore importance of variable
    anova(fit1, fit2);
    #Analysis of Variance Table
    #
    #Model 1: y ~ x1
    #Model 2: y ~ x1 + x2
    #  Res.Df     RSS Df Sum of Sq     F    Pr(>F)
    #1    998 1292.20
    #2    997  994.46  1    297.74 298.5 < 2.2e-16 ***
    #---
    #Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
    
    # Function to get estimates for parameter(s) par
    # from two models fit1 and fit2
    getEstimates <- function(par, fit1, fit2) {
        lst <- lapply(par, function(x)
            c(summary(fit1)$coef[x, 1], summary(fit2)$coef[x, 1]));
        names(lst) <- par;
        return(lst);
    }
    
    # Get coefficient for predictor x1
    est <- getEstimates("x1", fit1, fit2);
    

    根据getEstimates 的输出,您可以计算出两个模型之间某个参数的相对变化。

    # Calculate relative change in estimated x1 coefficient from both models
    lapply(est, function(x) abs(x[1] - x[2])/x[1]);
    #$x1
    #[1] 0.0282493
    

    【讨论】:

    • 感谢您的回复。当我尝试运行您的函数时出现此错误:“摘要错误(fit1)$coef[x, 1]:下标越界”。你知道为什么这可能是一个问题吗?我也在使用 GLM 函数,因为它是一个概率模型,以防万一发生任何变化。
    • @bbernicker 在没有任何示例数据的情况下调试有点困难。你是怎么打电话给getEstimates的?您能否dput(部分)您的源数据(或提供示例数据),并更新您的原始问题以包括glm 对两种不同模型的调用。 getEstimates 在我使用广义线性模型时仍然适用。
    • @bbernicker PS。显然getEstimates 仅适用于两个模型中都存在的预测器参数。所以在我的例子中,getEstimates("x2", fit1, fit2) 会抛出一个错误,因为fit1 不包含x2 作为模型预测器。您可以优化getEstimates 进行安全检查。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-27
    • 1970-01-01
    • 1970-01-01
    • 2019-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多