更改线性回归的 X 和 Y 变量

时间:2021-07-27 12:10:09

标签: r linear-regression

我目前正在查看我的数据中是否有年度趋势。我正在做 R 和年份、H 和年份以及 R 和 H 之间的线性回归。

但是,当我对 R 与年份进行线性回归时,我得到了 NA F 和 P 值。当年份是 y 时代码有效,但我想知道为什么线性模型只能以一种方式工作,如果年份为 y 在这种情况下对数据分析有效? 提前致谢。

数据:

<头>
R H
2000 160 140
2001 178 153
2002 149 138
2003 161 149
2004 180 173
2005 150 142
2006 158 130
2007 149 190
2008 167 200
2009 172 204

代码:

#this has lots of NA outputs
linearmodel<-lm(data$R ~ data$year)
linearmodel
summary(linearmodel)

#this gives output statistics
linearmodel<-lm(data$year ~ data$R)
linearmodel
summary(linearmodel)

再次感谢。

1 个答案:

答案 0 :(得分:1)

我无法重现这一点。这两个公式在输出中都不包含 NA 值。这两个模型的 summary() 也是如此。

data_68544559 <- data.frame(
  year = 2000:2009,
  R = c(160, 178, 149, 161, 180, 150, 158, 149, 167, 172)
)

lm(R ~ year, data_68544559)
#> 
#> Call:
#> lm(formula = R ~ year, data = data_68544559)
#> 
#> Coefficients:
#> (Intercept)         year  
#>   259.58788     -0.04848
lm(year ~ R, data_68544559)
#> 
#> Call:
#> lm(formula = year ~ R, data = data_68544559)
#> 
#> Coefficients:
#> (Intercept)            R  
#>   2.005e+03   -3.316e-03

将时间列的格式更改为 POSIXct 也不会给出 NA,但是 summary() 中会出现错误,因为无法计算残差。

summary(lm(ISOdate(year, 1, 1) ~ R, data_68544559))
#> Error in Ops.difftime((f - mean(f)), 2) : 
#>   '^' not defined for "difftime" objects