在 R 中使用回归方程进行预测

Prediction with regression equation in R

首先让我告诉你我是 R 的新手,所以我的问题对你来说可能听起来很奇怪,我想根据身高预测一个人的体重。为此,我需要找到此问题的回归线方程(以下形式):

重量=截距+(斜率)x高度

我有以下形式的数据?

关于如何找到回归线方程的任何想法

dat <- read.table(text = "SampleNo,Height,Weight
                          1,65.78,112.99
                          2,71.52,136.49
                          3,69.40,153.03
                          4,68.22,142.34
                          5,67.79,144.30
                          6,68.70,123.30
                          7,69.80,141.49
                          8,70.01,136.46
                          9,67.90,112.37", 
                  sep = ",", header = T)

您可以使用 lm 函数完成此操作。

lm1 <- lm(Weight ~ Height, data = dat )

我想预测 Weight 作为 Height 的函数,所以我使用语法 Weight ~ Height

最后,我 运行 lm1 对象上的 coefficients 函数来获取 Height 的系数和截距。

coefficients(lm1)
    (Intercept)      Height 
    -177.650244    4.525168 

如果我想预测 Weight 的某组 Heights 的结果,我可以使用以下方法:

> predict(lm1, newdata = data.frame((Height = c(65, 68.5, 71.6))))
       1        2        3 
116.4857 132.3238 146.3518 

您可以使用 lm1 对象上的 summary 函数获取有关拟合的更多信息。这将提供 R^2 值、有关估计的更多信息等...

summary(lm1)

Call:
lm(formula = Weight ~ Height, data = vals)

Residuals:
    Min      1Q  Median      3Q     Max 
-17.239  -9.500  -2.697  11.283  16.634 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept) -177.650    193.247  -0.919    0.389
Height         4.525      2.808   1.611    0.151

Residual standard error: 13.03 on 7 degrees of freedom
Multiple R-squared:  0.2705,    Adjusted R-squared:  0.1663 
F-statistic: 2.596 on 1 and 7 DF,  p-value: 0.1512

可以在 R 中找到用于回归和许多其他机器学习技术的重要(免费)资源 here。这是一本了解统计信息以及如何在 R 中实现这些方法的好书。