您没有提供任何示例数据,所以我将基于模型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