Why is this controversial?ġ) Loops are slow in R. This will result in foo.squared containing only one value – the last value calculated by the loop. You are missing your square brackets with a counter on the left side of the equal sign. About 45 minutes later I finally figured out what was wrong with my loop.ĭid you forget to subscript your new vector? Possibly the inside of your loop looks like this If you are having problems with your loop, it could be one of these silly mental slips.ĭid you reset your vector inside the loop? Is it possible you put a new.vector = NULL inside the loop instead of before it? Yeah, I’ve done it. However the 5th element of foo will be foo, which is equal to 9. 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).
#USING 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. Mean(trials) # mean(trials) = fraction that are 1's 0.There may be no R topic that is more controversial than the humble for-loop. Trials = (s = 0) # 1 if a derangement, 0 if not S = sum(y = x) # s = number of people in their original seat (A derangement is a permutation where no element ends up in its original position.) n = 9 # Let's estimate the probability of a derangement in a permutation of 9 objects. # for loops are truly valuable when the calculation is more complicated and we can't do it exactly or with built in R functions. Mean(trials^2) 15.207 # Of course we could have done this simulation without a loop. Trials = sample(1:nsides,1) # We get one sample at a time Sum(x) class='r'> 338350 # Let's use a for loop to estimate the average of squaring the result of a roll of a die. X class='r'> 1 4 9 16 25 # You always wanted to know the sum of the first 100 squares.
# First we create a vector and then we fill in its values n = 5 25 # We can capture the results of our loop in a list
# Loop through the sequence 1 to 5 printing the square of each number for (j in 1:5) X 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 for(i in x) # 'for loops' let us repeat (loop) through the elements in a vector and run the same code on each element X 0 0 0 0 0 0 0 0 0 0 # rep() will replicate almost anything x = rep(2,6) # rep(0, 10) makes a vector of of 10 zeros. R makes this easy with the replicate function rep() This is a short tutorial to explain 'for loops'.Ĭolor coding # Comments are in maroon Code is in black Results are in this green rep() # Often we want to start with a vector of 0's and then modify the entries in later code.