R does something a little unexpected -- well, unexpected to me -- with the indexing of the for loop (and maybe this is more general, I don't know).
If you have... (note I can't use "get" with the arrow made of brackets, Google does not parse that in terms of HTML and it kills the code...)
n = 5
for (i in 1 : n+1) {
do stuff
}
...the index is 2 to 6, not 1 to 6. The +1 gets added to both the indices.
So it's like (i in (1:n) + 1) kind of.
What you need is....
for (i in 1 : (n+1)) {....
This is related to off by one errors (humorous explanation and more serious explanation), but I certainly didn't expect it to be parsed like that.