隨機正常日期的簡單迴歸失敗,但具有小整數而不是日期的相同數據按預期工作。由於R中的大整數datetime,奇異線性模型?
# Example dataset with 100 observations at 2 second intervals.
set.seed(1)
df <- data.frame(x=as.POSIXct("2017-03-14 09:00:00") + seq(0, 199, 2),
y=rnorm(100))
#> head(df)
# x y
# 1 2017-03-14 09:00:00 -0.6264538
# 2 2017-03-14 09:00:02 0.1836433
# 3 2017-03-14 09:00:04 -0.8356286
# Simple regression model.
m <- lm(y ~ x, data=df)
由於數據中存在奇點,因此缺少斜率。調用摘要演示了這一點:
summary(m)
# Coefficients: (1 not defined because of singularities)
# Estimate Std. Error t value Pr(>|t|)
# (Intercept) 0.10889 0.08982 1.212 0.228
# x NA NA NA NA
難道這是因爲POSIXct
類嗎?
# Convert date variable to integer.
df$x2 <- as.integer(df$x)
lm(y ~ x2, data=df)
# Coefficients:
# (Intercept) x2
# 0.1089 NA
不,係數爲x2
仍然缺失。
如果我們使x2
的基線爲零會怎麼樣?
# Subtract minimum of x.
df$x3 <- df$x2 - min(df$x2)
lm(y ~ x3, data=df)
# Coefficients:
# (Intercept) x3
# 0.1312147 -0.0002255
This Works!
另一個例子來排除這是由於日期時間變量。
# Subtract large constant from date (data is now from 1985).
df$x4 <- df$x - 1000000000
lm(y ~ x4, data=df)
# Coefficients:
# (Intercept) x4
# 1.104e+05 -2.255e-04
不是所期望的(爲什麼一個具有30年差異的相同數據集會導致不同的行爲?),但是這也可以工作。
可能是.Machine$integer.max
(2147483647在我的電腦上)與它有關係,但我無法弄清楚。如果有人能夠解釋這裏發生了什麼,我們將不勝感激。
由於POSIXct原點完全是任意的,因此通常建議減去最小時間。它也使解釋係數更容易一些。 – Roland