使用带有lm()对象列表的预测 [英] using predict with a list of lm() objects
问题描述
我有定期进行回归分析的数据.每个大块"数据都适合不同的回归.例如,每个状态可能都有不同的函数来解释从属值.这似乎是一个典型的"split-apply-combine"类型的问题,因此我正在使用plyr软件包.我可以轻松创建一个效果很好的lm()
对象列表.但是,我无法完全理解以后如何使用这些对象来预测单独data.frame中的值.
I have data which I regularly run regressions on. Each "chunk" of data gets fit a different regression. Each state, for example, might have a different function that explains the dependent value. This seems like a typical "split-apply-combine" type of problem so I'm using the plyr package. I can easily create a list of lm()
objects which works well. However I can't quite wrap my head around how I use those objects later to predict values in a separate data.frame.
这是一个完全人为的例子,说明了我正在尝试做的事情:
Here's a totally contrived example illustrating what I'm trying to do:
# setting up some fake data
set.seed(1)
funct <- function(myState, myYear){
rnorm(1, 100, 500) + myState + (100 * myYear)
}
state <- 50:60
year <- 10:40
myData <- expand.grid( year, state)
names(myData) <- c("year","state")
myData$value <- apply(myData, 1, function(x) funct(x[2], x[1]))
## ok, done with the fake data generation.
require(plyr)
modelList <- dlply(myData, "state", function(x) lm(value ~ year, data=x))
## if you want to see the summaries of the lm() do this:
# lapply(modelList, summary)
state <- 50:60
year <- 50:60
newData <- expand.grid( year, state)
names(newData) <- c("year","state")
## now how do I predict the values for newData$value
# using the regressions in modelList?
那么我该如何使用modelList
中包含的lm()
对象来使用年份和状态独立于newData
的值来预测值?
So how do I use the lm()
objects contained in modelList
to predict values using the year and state independent values from newData
?
推荐答案
这是我的尝试:
predNaughty <- ddply(newData, "state", transform,
value=predict(modelList[[paste(piece$state[1])]], newdata=piece))
head(predNaughty)
# year state value
# 1 50 50 5176.326
# 2 51 50 5274.907
# 3 52 50 5373.487
# 4 53 50 5472.068
# 5 54 50 5570.649
# 6 55 50 5669.229
predDiggsApproved <- ddply(newData, "state", function(x)
transform(x, value=predict(modelList[[paste(x$state[1])]], newdata=x)))
head(predDiggsApproved)
# year state value
# 1 50 50 5176.326
# 2 51 50 5274.907
# 3 52 50 5373.487
# 4 53 50 5472.068
# 5 54 50 5570.649
# 6 55 50 5669.229
JD长时间编辑
我很受启发,制定了adply()
选项:
I was inspired enough to work out an adply()
option:
pred3 <- adply(newData, 1, function(x)
predict(modelList[[paste(x$state)]], newdata=x))
head(pred3)
# year state 1
# 1 50 50 5176.326
# 2 51 50 5274.907
# 3 52 50 5373.487
# 4 53 50 5472.068
# 5 54 50 5570.649
# 6 55 50 5669.229
这篇关于使用带有lm()对象列表的预测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!