

For example when we’ve looped through the instructions 4 times, the next loop will be loop number 5 (so i=5). If you are new to programming it is sometimes difficult to keep straight the difference in the number of loops you are on versus the value of the element of vector being operated on. For our new vector foo.squared, the ith element will equal the number of loops that we are on (for the first loop, i=1 second loop, i=2). The counter we set up is ‘i’ (but you can put whatever variable name you want there).
WRITING FOR LOOP IN R CODE
This code says we’ll loop 50 times( 1:50). So, we set up an empty vector to add stuff to later (note that this isn’t the most speed efficient way to do this, but it’s fairly fool-proof). R doesn’t like being told to operate on a vector that doesn’t exist yet. If the creation of a new vector is the goal, first you have to set up a vector to store things in prior to running the loop. I’m going to set up a loop to square every element of my dataset, foo, which contains the odd integers from 1 to 100 (keep in mind that vectorizing would be faster for my trivial example – see below). Use the for loop if you want to do the same task a specific number of times. ?'for' will get you the help page but it is by no means exhaustive.) So, at the request of Sam, a faithful reader of the Paleocave blog, I’m going to throw my hat into the ring and brace myself for the potential onslaught of internet troll wrath. In fact, even searching for help within R is not easy and not even that helpful when successful ( ?for won’t get you anywhere.

I was astounded by the lack of useful posts when I googled “for loops in R” (the top return linked to a page that did not exist). And, to top it off, good help is hard to find.
