I know that I should avoid for-loops, but I’m not exactly sure how to do what I want to do with an apply function.
Here is a slightly simplified model of what I’m trying to do. So, essentially I have a big matrix of predictors and I want to run a regression using a window of 5 predictors on each side of the indexed predictor (i in the case of a for loop). With a for loop, I can just say something like:
results<-NULL
window<-5
for(i in 1:ncol(g))
{
first<-i-window #Set window boundaries
if(first<1){
1->first
}
last<-i+window-1
if(last>ncol(g)){
ncol(g)->last
}
predictors<-g[,first:last]
#Do regression stuff and return some result
results[i]<-regression stuff
}
Is there a good way to do this with an apply function? My problem is that the vector that apply would be shoving into the function really doesn’t matter. All that matters is the index.
Using an
applyfunction to do your regression is mostly a matter of preference in this case; it can handle some of the bookkeeping for you (and so possibly prevent errors) but won’t speed up the code.I would suggest using vectorized functions though to compute your
first‘s andlast‘s, though, perhaps something like:Or be even smarter with
Then you could use this in a
forloop like this:or with
lapplylike this:where in both cases I just return the sequence between first and list; you would substitute with your actual regression code.