我如何仅使用前两个系数来解决绝对警告?

时间:2019-02-17 19:48:26

标签: r linear-regression

使用abline()时,我无法解决错误。我不断收到警告消息:在abline(model)中:仅使用7个回归系数中的前两个。我一直在搜索并看到许多其他实例出现此错误的情况,但它们的示例适用于多个线性函数。我是R的新手,下面是一个我正在使用的简单示例。感谢您的帮助!

year = c('2010','2011','2012','2013','2014','2015','2016')
population = c(25244310,25646389,26071655,26473525,26944751,27429639,27862596)
Texas=data.frame(year,population) 

plot(population~year,data=Texas)
model = lm(population~year,data=Texas)
abline(model)

1 个答案:

答案 0 :(得分:2)

您可能想要类似以下内容,以确保将year解释为模型中的numeric变量:

plot(population ~ year, data  =Texas)
model <- lm(population ~ as.numeric(as.character(year)), data=Texas)
abline(model)

enter image description here

这使得lm可以估算出截距(对应于0年)和斜率(每年的平均人口增长),abline可以正确地解释该斜率,也可以在图中看到

发出警告的原因是,年份成为7个级别的因数,因此您的lm通话估算参考年份2010(截距)的平均值,并与其他年份对比6。因此,您得到许多系数,abline仅使用前两个(不正确)。

编辑:话虽如此,您可能想更改将year存储为数字的方式。然后您的代码开始工作,plot还将绘制适当的散点图作为回归线。

Texas$year <- as.numeric(as.character(Texas$year))

plot(population ~ year, data=Texas, pch = 16)
model <- lm(population ~ year, data=Texas)
abline(model)

enter image description here

请注意,as.character通常是必需的,但巧合的是它可以在lm中使用(因为年份是连续的)