r - Predicting data via regression model and storing in a vector -
apologies basic question.
i have created linear model massive meteorological dataset using multiple regression. goal use model "predict" data during period using predictors 1, 2 , 3. compare predicted data observed data period.
my approach far has been create new vector predicted values , loop through vector, creating predicted values based on extracted coefficients of linear model. then, subtract predicted values observed values. reason, approach results in new predicted vector being null. idea how approach this?
a sample below. "data" refers dataset containing predictors.
coef <- coefficients(multipleregressionmodel) predictedvalues=c() for(i in 1:length(data$timeperiod)){ predictedvalues[i] = append(predictedvalues, data$coef[1]+data$predictor1[i]*data$coef[2]+data$predictor2[i]*data$coef[3]+ data$predictor3[i]*data$coef[4]) } diff=c() diff=observedvalues - predictedvalues
it looks making more difficult needs be. r has predict()
function of you. if had sample data.frame
so:
set.seed(26) mydf = data.frame (a=1:20 , b = rnorm(20), c = 1:20 + runif(20,2,3)*runif(20, 2, 3), d = 1:20 + rpois(20,5)*runif(1:20)*sin(1:20))
and wanted train on rows, , test on others
trainrows<-sample(1:20, 16) mydf.train<-mydf[trainrows,] mydf.test<-mydf[-trainrows,]
then fit model , predict
model<-lm(a~b+c+d, data = mydf.train) summary(model) #gives info model. mydf.test$pred<-predict(model1, newdata = mydf.test) mse<-mean((mydf.test$pred-mydf.test$a)^2) #calculate mean squared error mse #[1] 0.06321
view predictions mydf.test$pred
Comments
Post a Comment