一元线性拟合
- 数据:见http://pan.baidu.com/s/1qu6dq
-
options(scipen = 100) # 读文件 city_gdp <- read.table("D:/Sepcial_For_R/city_gdp.txt", sep = "\t", col.names=c("city", "people", "gdp"), head = T); # 散点图,y ~ x plot(city_gdp$gdp ~ city_gdp$people) # 多元线性拟合 # 线性拟合 lm(formula, data) # formula: 执行拟合的模型形式,y ~ x1+x2+x3 # data: 包含拟合模型的数据框 reg <- lm(city_gdp$gdp ~ city_gdp$people, data = city_gdp) # 拟合模型的详细结果 summary(reg) # 查看拟合模型的预测值 fitted(reg) # 查看拟合模型的残差值 residuals(reg) # 作图 plot(city_gdp$gdp ~ city_gdp$people, xlab="People", ylab="GDP") # 做拟合的直线 abline(reg, col='red')