Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy does R behave strangely with the lm.predict function, in the following code?
    primarykey
    data
    text
    <p>I have a problem with the code below, which I'm trying to understand:</p> <pre><code>x = rnorm(50) y = 3 * x +rnorm(50) df_eq &lt;- data.frame(x, y) model1 &lt;- lm(y ~ x - 1) model2 &lt;- lm(df_eq[,2] ~ df_eq[,1] - 1) xpred &lt;- data.frame(x = seq(from = -2, to = 2, length = 5)) ypred &lt;- predict(object = model1, newdata = xpred) ypred2 &lt;- predict(object = model2, newdata = xpred) </code></pre> <p>In the above code, I am expecting both ypred and ypred2 to produce the same outcomes. I get the answer i'm expecting in ypred (5 predicted "yhat" values), but ypred2 has an error, and doesn't produce what is expected.</p> <p>Can anyone please explain why, in the following code, ypred2 produces an error (in R 2.15.2 at least)? </p> <p>The only key difference in the code, I think, comes from the way "model1" and "model2" are produced.</p> <p>My understanding is that in the predict function, newdata produces the new set of observations which we want to predict "yhat" values for, based on the model as stored in model1 and model2 objects.</p> <p>What is fundamentally different about</p> <p>model1 &lt;- lm(y ~ x - 1)</p> <p>and</p> <p>model2 &lt;- lm(df_eq[,2] ~ df_eq[,1] - 1) ? </p> <p>More importantly, if the answer is straightforward, can somebody explain how they figured out the differences from "under the hood" of R? It would be nice to know how I could understand this kind of problem in the future. I've tried looking at the structures of the objects in the above code, but am no closer to an answer.</p> <p>Thank you in advance.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload