如何仅使用前两个系数来修复abline警告?

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

使用abline()时,我无法解决错误。我不断收到警告信息:在abline(模型)中:仅使用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)
r linear-regression
1个回答
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工作,没有巧合(因为年份是连续的)

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