我有一个包含数千个人数据的数据集,测量过去9年每年测量的参数X.
基本上它们位于数据帧df
中id,year,x,feature
A,2016,376,female
A,2015,391,female
A,2014,376,female
A,2013,373,female
A,2012,347,female
A,2011,330,female
B,2016,398,male
B,2015,391,male
B,2014,410,male
B,2013,393,male
B,2012,408,male
B,2011,288,male
C,2016,2464,male
C,2015,2465,male
C,2014,2500,male
C,2013,2215,male
C,2012,2228,male
C,2011,1839,male
等
我想估算这些时间序列的不同模型
像predict(x(t))= f(x(t-1),x(t-2),...,x(tn),feature,id(作为随机因子))
我可以看到如何使用ts进行自回归建模,但它会计算单个模型的thosands,我想要根据时间历史和特征进行全局预测(及其固有的问题)。
由于数据高度自相关,因此不是一个好主意。有什么好主意吗?答案 0 :(得分:1)
有许多可能的模型,但这里有一个AR1结构的混合效果模型,您可以尝试。
library(nlme)
fm <- lme(x ~ year + feature, random = ~ year | id, DF,
correlation = corAR1(form = ~ year | id))
summary(fm)
这是一个数据图:
library(ggplot2)
ggplot(DF, aes(year, x, group = id, col = feature)) + geom_line() + geom_point()
注意:我们假设了这个输入数据:
Lines <- "
id,year,x,feature
A,2016,376,female
A,2015,391,female
A,2014,376,female
A,2013,373,female
A,2012,347,female
A,2011,330,female
B,2016,398,male
B,2015,391,male
B,2014,410,male
B,2013,393,male
B,2012,408,male
B,2011,288,male
C,2016,2464,male
C,2015,2465,male
C,2014,2500,male
C,2013,2215,male
C,2012,2228,male
C,2011,1839,male"
library(zoo)
DF <- read.csv(text = Lines, strip.white = TRUE)
答案 1 :(得分:1)
关于函数f()
的陈述产生了许多选择。
但是,在线性类中,您可以使用向量广义线性模型 (通过vglm())来拟合具有ARMA(或GARCH)结构的广义线性模型, 纳入协变量。
例如,假设(预设的)随机错误是正态分布的,您可以使用包ARff()
中的族函数VGAMextra
,如下所示。
然而,第二选项通过智能预测使用非参数版本,即VGAM。 唯一的缺点是vglms / vgams不处理随机效果。
library(VGAM)
library(VGAMextra)
# Fitting a linear model to the mean of the normal distribution
# allowing an AR(3) struture. Use the modelling function vglm() and
# the family functions ARff()
df.read <- DF # DF as given by G.G.
fit.Lines <- vglm(x ~ feature , ARff(order = 3,
zero = c("Var", "ARcoeff")),
data = df.read, trace = TRUE)
coef(fit.Lines, matrix = TRUE)
summary(fit.Lines, HD = FALSE)
with(df.read, plot(fitted.values(fit.Lines) ~ year,
ylim = c(0, 3000),
pch = 19, col = as.factor(feature)))
# Using VGAMs, here, the family function uninormal() is utilized.
#
df.read2 <- data.frame(embed(df.read$x, 4))
names(df.read2) <- c("x", "xLag1", "xLag2", "xLag3")
df.read2 <- transform(df.read2, year = df.read$year[-c(1:3)],
feature = df.read$feature[-c(1:3)])
fit.Lines.vgams <- vgam(x ~ sm.bs(xLag1) + sm.bs(xLag2) +
sm.bs(xLag3) + feature + year,
uninormal, data = df.read2, trace = TRUE)
with(df.read2, plot(fitted.values(fit.Lines.vgams) ~ year,
ylim = c(0, 3000),
pch = 19, col = as.factor(feature)))