库library
库:一组不含在基础R配置内的函数和数据集
library(MASS) # 加载库
library(ISLR)# 安装库 install.packages("ISLR")
简单线性回归
fix(Boston) # 查看Boston数据集
names(Boston) # 查看数据集的列名(预测变量+响应变量medv)
- 'crim'
- 'zn'
- 'indus'
- 'chas'
- 'nox'
- 'rm'
- 'age'
- 'dis'
- 'rad'
- 'tax'
- 'ptratio'
- 'black'
- 'lstat'
- 'medv'
?Boston # 查看数据集的更多信息
线性拟合
# 方法一
lm.fit = lm(medv~lstat,data= Boston) # 指定数据集
# 方法二
attach(Boston) # 绑定数据集
lm.fit = lm(medv~lstat)
lm.fit # 给出拟合函数的基础信息
Call:
lm(formula = medv ~ lstat)
Coefficients:
(Intercept) lstat
34.55 -0.95
summary(lm.fit) # 给出拟合函数各类信息
Call:
lm(formula = medv ~ lstat)
Residuals:
Min 1Q Median 3Q Max
-15.168 -3.990 -1.318 2.034 24.500
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 34.55384 0.56263 61.41 <2e-16 ***
lstat -0.95005 0.03873 -24.53 <2e-16 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 6.216 on 504 degrees of freedom
Multiple R-squared: 0.5441, Adjusted R-squared: 0.5432
F-statistic: 601.6 on 1 and 504 DF, p-value: < 2.2e-16
names(lm.fit) # 列出拟合函数存储的所有信息种类
- 'coefficients'
- 'residuals'
- 'effects'
- 'rank'
- 'fitted.values'
- 'assign'
- 'qr'
- 'df.residual'
- 'xlevels'
- 'call'
- 'terms'
- 'model'
coef(lm.fit) # 提取拟合参数(系数估计值)
-
(Intercept) 34.5538408793831 lstat -0.950049353757991
confint(lm.fit) # 系数估计值的置信区间
2.5 % | 97.5 % | |
---|---|---|
(Intercept) | 33.448457 | 35.6592247 |
lstat | -1.026148 | -0.8739505 |
# 根据指定预测变量计算响应变量,同时给出置信空间或者预测空间
predict(lm.fit, data.frame(lstat=(c(5,10,15))), interval = "confidence") # 置信空间
fit | lwr | upr | |
---|---|---|---|
1 | 29.80359 | 29.00741 | 30.59978 |
2 | 25.05335 | 24.47413 | 25.63256 |
3 | 20.30310 | 19.73159 | 20.87461 |
predict(lm.fit, data.frame(lstat=(c(5,10,15))), interval = "prediction") # 预测空间
fit | lwr | upr | |
---|---|---|---|
1 | 29.80359 | 17.565675 | 42.04151 |
2 | 25.05335 | 12.827626 | 37.27907 |
3 |