[R] How to use lm.predict to obtain fitted values?

Prof Brian Ripley ripley at stats.ox.ac.uk
Fri May 19 19:26:04 CEST 2006


data.frame(x=newData)  will not have any entries called x:  You supplied 
newdata, so assuming you means newdata,

> data.frame(x=newdata)
   x.1 x.2 x.3 x.4 x.5 x.6
1   1   1   1   1   1   1

has 6 columns none of which is labelled x.

If you read the help for lm, it does not mention having a matrix on the 
rhs of a formula, and the help for data.frame does explain how it works.

predict(model, data.frame(x=I(newData)))

might work.

On Fri, 19 May 2006, Richard Lawn wrote:

> I am writing a function to assess the out of sample predictive capabilities
> of a time series regression model.  However lm.predict isn't behaving as I
> expect it to.  What I am trying to do is give it a set of explanatory
> variables and have it give me a single predicted value using the lm fitted
> model.
>
>>     model = lm(y~x)
>>     newdata=matrix(1,1,6)
>>     pred = predict.lm(model,data.frame(x=newData));
> Warning message:
> 'newdata' had 6 rows but variable(s) found have 51 rows.
>>     pred = predict.lm(model,data.frame(newData));
> Warning message:
> 'newdata' had 6 rows but variable(s) found have 51 rows.
>
> y is a vector of length 51.
> x is a 6x51 matrix
> newdata is a matrix of the explanatory variables I'd like a prediction for.
>
> The predict.lm function is giving me 51 (=number of observations I had)
> numbers, rather than the one number I do want - the predicted value of y,
> given the values of x I have supplied it.
>
> Many thanks,
> R
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
>

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



More information about the R-help mailing list