#R-function for cross-validated R2 (see pages 49-52 i BS)
# Below is given a function that may compute cross-validated R2 (see pages 49-52 i BS)
# Copy the commands and paste them into the command-window of R:
kryssvalidR2<-function(lmobj,y=lmobj$y,x=lmobj$x)
{
? ?a=t(x)%*%x
? ?d=diag(1/eigen(a)$values)
??e=eigen(a)$vector
? ?inv.a=e %*% d %*% t(e)
? ?v<-diag(x%*%inv.a%*%t(x))
? ?SSkryss<-sum((lmobj$res/(1-v))^2)
? ?SStot<-sum((y-mean(y))^2)
? ?R2kryss<-1-SSkryss/SStot
? ?R2kryss
}
# To use the function, you first fit a linear regression model by a command of the form lmobj<-lm(y~x1+x2+x3+x4+x5, x=T, y=T)
# (note that you need to include the options "x=T" and "y=T")
# Then you compute cross-validated R2 by the command kryssvalidR2(lmobj)