title: Mean Square Prediction Error (MSPE) on out of sample data in R
body: <p>I want to calculate the <strong>out of sample</strong> MSPE for a multiple linear regression using R. From my textbook I got the following formula for MSPE</p>
  <p><a href="https://i.stack.imgur.com/f01EF.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/f01EF.gif" alt="enter image description here" /></a></p>
  <p>where <a href="https://i.stack.imgur.com/AcBPd.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AcBPd.gif" alt="enter image description here" /></a> meaning that observation <em>i</em> have been omitted from the mean.</p>
  <p>I tried calculating the MSEP by using the following two lines in R</p>
  <pre><code>fit &lt;- lm(CO ~ weight + nico, data = df)
  mean( (df$CO - predict.lm(fit, df))^2 )
  </code></pre>
  <p>However I'm fairly sure that this is in-sampel MSPE. I tried to hardcode the MSPE and ended up with</p>
  <pre><code>MSEP &lt;- function(df){
    df &lt;- df[, -1] # Removing &quot;name&quot; column
    factor &lt;- 1/nrow(df)
    summa &lt;- 0
    for(i in 1:nrow(df)){
      df_ny &lt;- df[-i, ]
      fit &lt;- lm(CO ~., data = df_ny)
      holder &lt;- (df[i,]$CO - predict.lm(fit, df[i, ]))^2
      summa &lt;- summa + holder
    }
    return(factor*summa)
  }
  </code></pre>
  <p>Is this correct? Is there a built in function in R I can use to compare my result?</p>
  <p>Thanks in advance.</p>