Sankalp Sharma
Sankalp Sharma

Reputation: 45

Looping over objects in R

I am trying to loop over objects in R.

myfunc.linear.pred <- function(x){
  linear.pred <- predict(object = x)
  w <- exp(linear.pred)/(1+exp(linear.pred))
  as.vector(w)
}

The function here works perfectly as it should. It returns a vector of 48 rows and it comes from the object x. Now 'x' is nothing but the full regression model from a GLM function (think: mod.fit <- glm (dep~indep, data = data)). The problem is that I have 20 different such ('mod.fit') objects and need to find predictions for each of these. I could literally repeat the code, but I was looking to find a neater solution. So what I want is a matrix with 48 rows and 20 columns for the above function. This is probably basic for an advanced user, but I have only ever used "apply" and "for" loops for numbers and never objects. I looked into lapply but couldn't figure it out.

I tried: (and this is probably dumb)

allmodels <- c(mod.fit, mod.fit2, mod.fit3)
lpred.matrix <- matrix(data=NA, nrow=48, ncol=20)
for(i in allmodels){
  lpred.matrix[i,] <- myfunc.linear.pred(i)
}

which obviously won't work because allmodels has a class of "list" and it contains all the stuff from the GLM function. Hope someone can help. Thanks!

Upvotes: 1

Views: 714

Answers (1)

Harry Smith
Harry Smith

Reputation: 278

In order to use lapply, you must have a list object not a vector object. Something like this should work:

## Load data
data("mtcars")

# fit models
mod.fit1 <- glm (mpg~disp, data = mtcars)
mod.fit2 <- glm (mpg~drat, data = mtcars)
mod.fit3 <- glm (mpg~wt, data = mtcars)

# build function
myfunc.linear.pred <- function(x){
  linear.pred <- predict(object = x)
  w <- exp(linear.pred)/(1+exp(linear.pred))
  as.vector(w)
}

# put models in a list
allmodels <- list("mod1" = mod.fit1, "mod2" = mod.fit2, "mod2" = 
mod.fit3)

# use lapply and do.call to generate matrix of prediction results
df <- do.call('cbind', lapply(allmodels, function(x){
  a <- myfunc.linear.pred(x)
}))

Hope this helps

Upvotes: 1

Related Questions