Search code examples
rdataframefunctionvectormodel

Extracting R2 from models and storing them into a vector in R?


I am building models in R, and would like to extract the R2 values of those models and store them into a vector.

Here is a simplified dataframe showing the speed of 6 bears in relation to their sex, mass, year and ambient temperature:

speed<-c(0.5,0.1,0.3,0.4,0.9,0.2)
sex<-c(rep(c("F","M"),times=c(3,3)))
mass<-c(500,400,600,800,700,500)
year<-c(2000,2000,2001,2001,2002,2002)
temp.c<-c(0,2,3,1,3,0)
data<-data.frame(speed,sex,mass,year,temp.c)
data

  speed sex mass year temp.c
1   0.5   F  500 2000      0
2   0.1   F  400 2000      2
3   0.3   F  600 2001      3
4   0.4   M  800 2001      1
5   0.9   M  700 2002      3
6   0.2   M  500 2002      0

And here are three models to work with:

full<-glm(formula = speed ~ sex + mass + year + temp.c, data=data,family=Gamma)
bio<-glm(formula = speed ~ sex + mass, data=data,family=Gamma)
clim<-glm(formula = speed ~ year + temp.c, data=data,family=Gamma)

Finally, I have already created a function to extract R2 from the models:

R2<-function(x){
  psdR2<-cor(data$speed,predict(x))^2
  return(psdR2)
}

In order to extract R2 from all three models automatically and store them into a vector, I have tried the following code, but this does not work and I get an error.

mods<-c(full,bio,clim)
r2.vec<-lapply(mods,R2)

Error in UseMethod("predict") : 
  no applicable method for 'predict' applied to an object of class "c('double', 'numeric')"

I'm not sure what to do after this. Any suggestions?


Solution

  • Use

    mods <- list(full, bio, clim)
    

    not

    mods<- c(full, bio, clim)
    

    You want a list of three models, you don't want to combine the models into a single object. You can see the difference with

    length(list(full,bio,clim))
    # [1] 3
    length(c(full,bio,clim))
    # [1] 90