对R中的组进行回归和预测 [英] Make regressions and predictions for groups in R
问题描述
我从实验中获得了以下data.frame d
:
I have the following data.frame d
from an experiment:
- Variable y (response, continuous)
- Factor f (500 levels)
- Time t (posixct)
在过去的8年中,每个f级别的y大约每个月测量一次(确切的日期为t).有时每月有2项措施,有时过了几个月却没有采取任何措施.
In the last 8 years, y was measured roughly once a month (exact date in t) for each level of f. Sometimes there are 2 measures per month, sometimes a couple of month passed without any measures.
很抱歉,没有提供示例数据,但是弥补了不规则的时间序列超出了我的R知识. ;)
Sorry for not providing example data, but making up unregular time series goes beyond my R knowledge. ;)
我想对这些数据进行以下操作:
I'd like to do the following with this data:
- 对于每个级别的
f
,使用loess()
函数(y ~ t)
进行回归. - 对每个月的第一天和每个水平的
f
做出y
的预测
- make a regression using the
loess()
function(y ~ t)
, for each level off
- make a prediction of
y
for the first day of each month and each level off
我想通过使用Hadleys回答此来解决的第一点
The first point I think I solved by using Hadleys answer to this question:
models <- dlply(d, "f", function(df) loess(y ~ as.numeric(t), data = df))
所以,现在我有一个models
(类list
),每个f
级别都有一个模型.
我还创建了一些时间,对于每个时间,我都希望为f
的每个水平预测y
:
So, now I have a models
(class list
), with a model for each level of f
.
I also created times for which I'd like to predict y
for each level of f
like this:
dates <- seq(min(t),max(t),"months")
但是,现在我仍然停留在如何为每个模型进行预测上.像这样的东西应该可以工作(伪代码):
But now I'm stuck on how to make predictions for each model. Something like this should work (pseudocode):
for each f in models
p.f <- predict(models(f),dates)
p.f.complete <- r.bind(p.f.comlete,p.f)
next f
因此,我想要这个data.frame:
As a result, I'd like to have this data.frame:
- y.predicted
- f
- t.predicted(=日期)
任何帮助将不胜感激.
Any help would be greatly appreciated.
推荐答案
要做的最复杂的事情是将函数设置为predict
并使用lapply
.这不是很难做到.
The most complicated thing to do is make the function to predict
and ussing lapply
. Which is not very hard to do.
dates <- data.frame(t = dates)
y.predicted <- lapply(models, function (x) predict(x, newdata = dates))
如果您要预测y.predicted,请使用
if you want to rbind y.predicted just use
y.predicted <- do.call(rbind, y.predicted)
HTH
这篇关于对R中的组进行回归和预测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!