问题
Is there any difference between the predict()
and forecast()
functions in R?
If yes, in which specific cases should they be used?
回答1:
Intro
predict
-- for many kinds of R objects (models). Part of the base library.forecast
-- for time series. Part of the forecast package. (See example).
Example
#load training data
trnData = read.csv("http://www.bodowinter.com/tutorial/politeness_data.csv")
model <- lm(frequency ~ attitude + scenario, trnData)
#create test data
tstData <- t(cbind(c("H1", "H", 2, "pol", 185),
c("M1", "M", 1, "pol", 115),
c("M1", "M", 1, "inf", 118),
c("F1", "F", 3, "inf", 210)))
tstData <- data.frame(tstData,stringsAsFactors = F)
colnames(tstData) <- colnames(trnData)
tstData[,3]=as.numeric(tstData[,3])
tstData[,5]=as.numeric(tstData[,5])
cbind(Obs=tstData$frequency,pred=predict(model,newdata=tstData))
#forecast
x <- read.table(text='day sum
2015-03-04 44
2015-03-05 46
2015-03-06 48
2015-03-07 48
2015-03-08 58
2015-03-09 58
2015-03-10 66
2015-03-11 68
2015-03-12 85
2015-03-13 94
2015-03-14 98
2015-03-15 102
2015-03-16 102
2015-03-17 104
2015-03-18 114', header=TRUE, stringsAsFactors=FALSE)
library(xts)
dates=as.Date(x$day,"%Y-%m-%d")
xs=xts(x$sum,dates)
library("forecast")
fit <- ets(xs)
plot(forecast(fit))
forecast(fit, h=4)
来源:https://stackoverflow.com/questions/31409591/difference-between-forecast-and-predict-function-in-r