(Note: this was initially posted on my other blog at Glacial Till, but there were some good bits of information that I wanted to share with the Paleoposse.)
Last week I attended my first science conference: The Lunar and Planetary Science Conference in Houston, TX. If you followed me on Twitter, then (for better or for worse) you also knew that I was one of about 40 people microblogging the conference. There was a lot of great science to cover and it was fun trying to distill that information into 140 character limit. I got to present a poster on the shock dike that I’ve been working on for over a year now and I received good feedback on the research. I also met a lot of great people, some of whom will be potential collaborators in research and outreach projects.
There may be no R topic that is more controversial than the humble for-loop. And, to top it off, good help is hard to find. 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). In fact, even searching for help within R is not easy and not even that helpful when successful (?for won’t get you anywhere. ?'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.
How to loop in R
Use the for loop if you want to do the same task a specific number of times.
It looks like this.
for (counter in vector) {commands}
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).
foo = seq(1, 100, by=2)
foo.squared = NULL
for (i in 1:50 ) {
foo.squared[i] = foo[i]^2
}
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. This is the foo.squared = NULL part. This was a hard lesson for me to learn. R doesn’t like being told to operate on a vector that doesn’t exist yet. 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). Next, the real for-loop begins. This code says we’ll loop 50 times(1:50). The counter we set up is ‘i’ (but you can put whatever variable name you want there). 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). Continue reading Writing a for-loop in R→