r语言 - 从公式中连续删除预测变量



>我有一个模型公式,形式为

model.all <- lme(Response ~ A + B + C)

我想通过从模型中连续删除预测变量来更新此模型,因此我最终会得到 3 个模型,特别是:

mod.1 <- lme(Response ~ B + C) ; mod.2 <- lme(Response ~ A + C) ; mod.3 <- lme(Response ~ A + B) 

我正在考虑一个循环函数,所以我知道update函数,但我有太多的预测变量来手动更改代码。

任何建议将不胜感激。

在这种情况下我会使用combn,请参阅下面的示例:

示例数据

Response <- runif(100)
A <- runif(100)
B <- runif(100)
C <- runif(100)

溶液

a <- c('A','B','C')  #the names of your variables
b <- as.data.frame(combn(a,2)) #two-way combinations of those using combn
#create the formula for each model
my_forms <- sapply(b, function(x)   paste('Response ~ ', paste(x,collapse=' + '))) 
> my_forms #the formulas that will be used in the model
                 V1                  V2                  V3 
"Response ~  A + B" "Response ~  A + C" "Response ~  B + C" 
#run each model
my_models <- lapply(my_forms, function(x)  lm(as.formula(x))) 

输出

> summary(my_models[[1]])
Call:
lm(formula = as.formula(x))
Residuals:
     Min       1Q   Median       3Q      Max 
-0.48146 -0.20745 -0.00247  0.24263  0.58341 
Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept)  0.32415    0.08232   3.938 0.000155 ***
A            0.25404    0.09890   2.569 0.011733 *  
B            0.07955    0.10129   0.785 0.434141    
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 0.2828 on 97 degrees of freedom
Multiple R-squared:  0.06507,   Adjusted R-squared:  0.04579 
F-statistic: 3.375 on 2 and 97 DF,  p-value: 0.03827

如您所见,每个模型都保存为my_models中的列表元素。我发现这很容易制作和运行。

最新更新