# For loop step including last value

I've got the following code. I want to loop through my dataset (which is a matrix) in steps of let's say 50.000 and perform biglm on it.

lengthdata <- 100340
stepsize <- 50000

for (i in seq(1, lengthdata, stepsize)){
if(i+stepsize > lengthdata){
## call function (i, lengthdata)
print(paste(i, " - ", lengthdata))
}
else {
## call function (i, i+stepsize)
print(paste(i, " - ", i + stepsize))
}
}


This is my output:

 "1  -  50001"
 "50001  -  100001"
 "100001  -  100340"


Is there a more effective or cleaner way of coding this? I'm quite unexperienced using R!

You can save some typing if you declare a variable for where your range ends:

for (start.i in seq(1, lengthdata, stepsize)){
end.i <- if (i + stepsize > lengthdata) lengthdata else i + stepsize
## call function (start.i, end.i)
print(paste(start.i, " - ", end.i))
}


Another improvement would be to compute end.i using the min function (less typing!)

end.i <- min(start.i + stepsize, lengthdata)


As you become an advance user, you might like working with vectors directly:

start.i <- seq(1, lengthdata-1, stepsize)
end.i   <- pmin(start.i + stepsize, lengthdata)


and call your function(s) (e.g. paste) on all using the Map (or mapply)

output <- Map(paste, start.i, " - ", end.i)


rather than use a for loop (even less typing). This is equivalent to doing:

output <- list()
for (i in 1:length(start.i)) {
output[[i]] <- paste(start.i[i], " - ", end.i[i])
}