本文介绍了使用R比较线性回归与因子和滞后预测变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一段不错的R代码,用于拟合和可视化替代线性模型,网址为www.alastairsanderson.com/R/tutorials/linear-regression-with-a-factor/.我如何可能通过使用dyn或dynlm来概括该框架以允许滞后的预测变量?

There is a nice piece of R code for fitting and visualising alternative linear models at www.alastairsanderson.com/R/tutorials/linear-regression-with-a-factor/. How do I possibly generalise this framework to allow for lagged predictors, e.g., by using dyn or dynlm?

推荐答案

尝试一下:

library(dyn)
library(ggplot2)

forms.ch <- c(
     "y ~ x",
     "y ~ class / x",
     "y ~ class / Lag(x, 0:1)",
     "y ~ class / Lag(x, 0:2)"
)
forms <- sapply(forms.ch, as.formula)
Lag <- function(x, k = 1) lag(x, -k)

# L is a list of zoo objects which is fit to each formula
L <- lapply(mydata, zoo, order.by = mydata$x)
models <- lapply(forms, dyn$lm, data = L)

# create zero width zoo object, width0, which is merged with fitted.  fitted would
# otherwise be shorter than mydata (since we can't fit points at beginning due to
# lack of laggged points at boundary).  Also we convert mydata$x to numeric,
# from integer, to avoid warnings later on.
width0 <- zoo(, as.numeric(mydata$x))
models.sum <- lapply(models, function(x)
    data.frame(mydata,
        fitted = coredata(merge(fitted(x), width0)),
        strip = paste(format(formula(x)), "AIC:", round(AIC(x), 1)),
        formula = format(formula(x))
    )
)
models.long <- na.omit(do.call(rbind, models.sum))
models.long$class[ models.long$formula == forms.ch[1] ] <- NA # first model has no class
ggplot(models.long, aes(x, y, colour = class)) +
    geom_line(aes(y = fitted)) +
    geom_point() +
    facet_wrap(~ strip)

这篇关于使用R比较线性回归与因子和滞后预测变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 06:59