Hello,

lm() is designed to work with data.frames, not with matrices. You can change your code to something like

dat <- data.frame(price, pred1 = c(5,6,3,4,5), pred2 = c(2,1,8,5,6))
fit <- lm(price ~ pred1 + pred2, data = dat)

and then use the fitted model to do predictions. You don't have to give the new values in a matrix, you can give them as vectors of a data.frame.

predict(fit, data.frame(pred1 = 1:3, pred2 = 3:5))


Hope this helps,

Rui Barradas

Em 29-05-2014 21:38, Safiye Celik escreveu:
I want to perform a multiple regression in R and make predictions based on
the trained model. Below is an example code I am using:

price = c(10,18,18,11,17)
predictors = cbind(c(5,6,3,4,5),c(2,1,8,5,6))
predict(lm(price ~ predictors), data.frame(predictors=matrix(c(3,5),nrow=1)))

  So, based on the 2-variate regression model trained by 5 samples, I want
to make a prediction for the test data point where the first variate is 3
and second variate is 5. But I get a warning from above code saying
that 'newdata'
had 1 rows but variable(s) found have 5 rows. How can I correct above code?
Below code works fine where I give the variables separately to the model
formula. But since I will have hundreds of variates, I have to give them in
a matrix since it would be unfeasible to append hundreds of columns using +
  sign.

price = c(10,18,18,11,17)
predictor1 = c(5,6,3,4,5)
predictor2 = c(2,1,8,5,6)
predict(lm(price ~ predictor1 + predictor2),
data.frame(predictor1=3,predictor2=5))

  Thanks in advance!


______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to