<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/loops-and-pizzas/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://msperlin.github.io/2018-10-19-R-and-loops/"> Marcelo S. Perlin</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p> An Introduction to Loops in R – </p>
<h1>Loops in R</h1>
<p>First, if you are new to programming, you should know that loops are a<br>
way to tell the computer that you want to repeat some operation for a<br>
number of times. This is a very common task that can be found in many<br>
programming languages. For example, let’s say you invited five friends<br>
for dinner at your home and the whole cost of four pizzas will be split<br>
evenly. Assume now that you <strong>must</strong> give instructions to a computer on<br>
calculating how much each one will pay at the end of dinner. For that,<br>
you need to sum up the individual tabs and divide by the number of<br>
people. Your instructions to the computer could be: <em>start with a value<br>
of x=zero, take each individual pizza cost and sum it to x until all<br>
costs are processed, dividing the result by the number of friends at the<br>
end</em>.</p>
<p>The great thing about <em>loops</em> is that the length of it is dynamically<br>
set. Using the previous example, if we had 500 friends (and a large<br>
dinner table!), we could use the same instructions for calculating the<br>
individual tabs. That means we can encapsulate a generic procedure for<br>
processing any given number of friends at dinner. With it, you have at<br>
your reach a tool for the execution of any sequential process. In other<br>
words, you are the boss of your computer and, as long as you can write<br>
it down clearly, you can set it to do any kind of repeated task for you.</p>
<p>Now, about the code, we could write the solution to the <em>pizza problem</em><br>
in R as:</p>
<div>
<div>
<pre><code>pizza.costs &lt;- c(50, 80, 30, 60) # each cost of pizza
n.friends &lt;- 5 # number of friends

x &lt;- 0 # set first cost to zero
for (i.cost in pizza.costs) {
  x &lt;- x + i.cost # sum it up
}

x &lt;- x/n.friends # divide for average per friend
print(x)

## [1] 44
</code></pre>
</div>
</div>
<p>Don’t worry if you didn’t understand the code. We’ll get to the<br>
structure of a loop soon.</p>
<p>Back to our case, each friend would pay 44 for the meal. We can check<br>
the result against function <code>sum</code>:</p>
<div>
<div>
<pre><code>x == sum(pizza.costs)/n.friends

## [1] TRUE
</code></pre>
</div>
</div>
<p>The output <code>TRUE</code> shows that the results are equal.</p>
<h2>The Structure of a Loop</h2>
<p>Knowing how to use loops can be a powerful ally in a complex data<br>
related problem. Let’s talk more about how <em>loops</em> are defined in R. The<br>
structure of a <em>loop</em> in R follows:</p>
<div>
<div>
<pre><code>for (i in i.vec){
  ...
}
</code></pre>
</div>
</div>
<p>In the previous code, command <code>for</code> indicates the beginning of a <em>loop</em>.<br>
Object <code>i</code> in <code>(i in i.vec)</code> is the iterator of the <em>loop</em>. This<br>
iterator will change its value in each iteration, taking each individual<br>
value contained in <code>i.vec</code>. Note the <em>loop</em> is encapsulated by curly<br>
braces (<code>{}</code>). These are important, as they define where the <em>loop</em><br>
starts and where it ends. The indentation (use of bigger margins) is<br>
also important for visual cues, but not necessary. Consider the<br>
following practical example:</p>
<div>
<div>
<pre><code># set seq
my.seq &lt;- seq(-5,5)

# do loop
for (i in my.seq){
  cat(paste('\nThe value of i is',i))
}

## 
## The value of i is -5
## The value of i is -4
## The value of i is -3
## The value of i is -2
## The value of i is -1
## The value of i is 0
## The value of i is 1
## The value of i is 2
## The value of i is 3
## The value of i is 4
## The value of i is 5
</code></pre>
</div>
</div>
<p>In the code, we created a sequence from -5 to 5 and presented a text for<br>
each element with the <code>cat</code> function. Notice how we also broke the<br>
prompt line with <code>'\n'</code>. The <em>loop</em> starts with <code>i=-5</code>, execute command<br>
<code>cat(paste('\nThe value of i is', -5))</code>, proceed to the next iteration<br>
by setting <code>i=-4</code>, rerun the <code>cat</code> command, and so on. At its final<br>
iteration, the value of <code>i</code> is <code>5</code>.</p>
<p>The iterated sequence in the <em>loop</em> is not exclusive to numerical<br>
vectors. Any type of vector or list may be used. See next:</p>
<div>
<div>
<pre><code># set char vec
my.char.vec &lt;- letters[1:5]

# loop it!
for (i.char in my.char.vec){
  cat(paste('\nThe value of i.char is', i.char))
}

## 
## The value of i.char is a
## The value of i.char is b
## The value of i.char is c
## The value of i.char is d
## The value of i.char is e
</code></pre>
</div>
</div>
<p>The same goes for <code>lists</code>:</p>
<div>
<div>
<pre><code># set list
my.l &lt;- list(x = 1:5, 
             y = c('abc','dfg'), 
             z = factor('A','B','C','D'))

# loop list
for (i.l in my.l){
  
  cat(paste0('\nThe class of i.l is ', class(i.l), '. '))
  cat(paste0('The number of elements is ', length(i.l), '.'))
  
}

## 
## The class of i.l is integer. The number of elements is 5.
## The class of i.l is character. The number of elements is 2.
## The class of i.l is factor. The number of elements is 1.
</code></pre>
</div>
</div>
<p>In the definition of <em>loops</em>, the iterator does not have to be the only<br>
object incremented in each iteration. We can create other objects and<br>
increment them using a simple sum operation. See next:</p>
<div>
<div>
<pre><code># set vec and iterators
my.vec &lt;- seq(1:5)
my.x &lt;- 5
my.z &lt;- 10

for (i in my.vec){
  # iterate &quot;manually&quot;
  my.x &lt;- my.x + 1
  my.z &lt;- my.z + 2
  
  cat('\nValue of i = ', i, 
      ' | Value of my.x = ', my.x, 
      ' | Value of my.z = ', my.z)
}

## 
## Value of i =  1  | Value of my.x =  6  | Value of my.z =  12
## Value of i =  2  | Value of my.x =  7  | Value of my.z =  14
## Value of i =  3  | Value of my.x =  8  | Value of my.z =  16
## Value of i =  4  | Value of my.x =  9  | Value of my.z =  18
## Value of i =  5  | Value of my.x =  10  | Value of my.z =  20
</code></pre>
</div>
</div>
<p>Using nested <em>loops</em>, that is, a <em>loop</em> inside of another <em>loop</em> is also<br>
possible. See the following example, where we present all the elements<br>
of a matrix:</p>
<div>
<div>
<pre><code># set matrix
my.mat &lt;- matrix(1:9, nrow = 3)

# loop all values of matrix
for (i in seq(1,nrow(my.mat))){
  for (j in seq(1,ncol(my.mat))){
    cat(paste0('\nElement [', i, ', ', j, '] = ', my.mat[i,j]))
  }
}

## 
## Element [1, 1] = 1
## Element [1, 2] = 4
## Element [1, 3] = 7
## Element [2, 1] = 2
## Element [2, 2] = 5
## Element [2, 3] = 8
## Element [3, 1] = 3
## Element [3, 2] = 6
## Element [3, 3] = 9
</code></pre>
</div>
</div>
<h2>A Real World Example</h2>
<p>Now, the computational needs of the real world is far more complex than<br>
dividing a dinner expense. A practical example of using <em>loops</em> is<br>
processing data according to groups. Using an example from Finance, if<br>
we have a return dataset for several stocks and we want to calculate the<br>
average return of each stock, we can use a <em>loop</em> for that. In this<br>
example, we will use <em>Yahoo Finance</em> data from three stocks: FB, GE and<br>
AA. The first step is downloading it with package <code>BatchGetSymbols</code>.</p>
<div>
<div>
<pre><code>library(BatchGetSymbols)

## Loading required package: rvest

## Loading required package: xml2

## Loading required package: dplyr

## 
## Attaching package: 'dplyr'

## The following objects are masked from 'package:stats':
## 
##     filter, lag

## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union

## 

my.tickers &lt;-  c('FB', 'GE', 'AA')

df.stocks &lt;- BatchGetSymbols(tickers = my.tickers, 
                             first.date = '2012-01-01', 
                             freq.data = 'yearly')[[2]]

## 
## Running BatchGetSymbols for:
##    tickers = FB, GE, AA
##    Downloading data for benchmark ticker | Found cache file
## FB | yahoo (1|3) | Found cache file - Good job!
## GE | yahoo (2|3) | Found cache file - Nice!
## AA | yahoo (3|3) | Found cache file - You got it!
</code></pre>
</div>
</div>
<p>It worked fine. Let’s check the contents of the dataframe:</p>
<div>
<div>
<pre><code>dplyr::glimpse(df.stocks)

## Observations: 21
## Variables: 10
## $ ticker              </code></pre></div></div>