I need to fit a glm to each row of a matrix. I can write a for loop to do this. I can also do it using apply, which is what usually seems to be recommended. However, the code runs faster using the for loop. Can someone tell me why this is, and what is the proper way to code something like this?
#some dummy data
response_mat<-matrix(0,10000,100)
response_mat<-apply(response_mat, c(1,2), function(x) sample(c(0,1),1))
predictor<-rnorm(100)
#fit glm to each row using a for loop
ptm <- proc.time()
for (i in 1:nrow(response_mat)){
model<-glm(response_mat[i,]~predictor,family="binomial")}
proc.time() - ptm
#fit glm using apply
glm_function<-function(x){model<-glm(x~predictor,family="binomial")}
ptm <- proc.time()
apply(response_mat,1,glm_function)
proc.time() - ptm