当回归有一个因子时,R中的预测值

问题描述 投票:-1回答:2

我有以下回归:

a <- lm(y ~ factor(x) + z + factor(x) * z, data = dataset)

对于不同的z水平,我想获得x = 1时的预测值。我一直在努力用predict包来做这件事。

任何帮助将不胜感激。

r regression predict
2个回答
0
投票
a <- lm(y ~ factor(x) + z + factor(x)*z, data=dataset)
df <- data.frame(x = c(1,1,1), z = c(1,2,3))
predict(a, df)

上面的想法是创建一个数据框,其值为XZ,您想要测试您的模型。


0
投票

对于将来的发布,最好始终包含样本数据。请参阅here how to provide a minimal reproducible example/attempt,包括样本数据。

除此之外,这是一个基于我生成的一些示例数据的简单示例。

# Generate sample data
set.seed(2017);
x <- as.numeric(gl(2, 10, 20));
z <- 1:20;
y <- 4 * x + 0.5 * z + rnorm(20);

# Fit model
fit <- lm(y ~ as.factor(x) + z + as.factor(x) * z);
summary(fit);
#    
#Call:
#lm(formula = y ~ as.factor(x) + z + as.factor(x) * z)
#
#Residuals:
#    Min      1Q  Median      3Q     Max
#-1.9283 -0.4702 -0.1270  0.7932  1.6648
#
#Coefficients:
#                Estimate Std. Error t value Pr(>|t|)
#(Intercept)      4.13695    0.79828   5.182 9.08e-05 ***
#as.factor(x)2    5.72079    2.17955   2.625  0.01839 *
#z                0.47615    0.12865   3.701  0.00194 **
#as.factor(x)2:z -0.09588    0.18195  -0.527  0.60544
#---
#Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
#
#Residual standard error: 1.169 on 16 degrees of freedom
#Multiple R-squared:  0.9522,   Adjusted R-squared:  0.9432
#F-statistic: 106.3 on 3 and 16 DF,  p-value: 8.896e-11

# Predict for x = 1, and y = 1:5
predict(fit, newdata = data.frame(x = 1, z = 1:5));
#1        2        3        4        5
#4.613097 5.089242 5.565388 6.041533 6.517679

请注意,如果您想根据预测变量的新值predict响应,则需要提供newdata data.frame。否则,predict将根据您的原始数据预测响应。

© www.soinside.com 2019 - 2024. All rights reserved.