<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/parallel-computing-exercises-foreach-and-doparallel-part-2/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://www.r-exercises.com/2017/07/13/parallel-computing-exercises-foreach-and-doparallel-part-2/?utm_source=rss&utm_medium=rss&utm_campaign=parallel-computing-exercises-foreach-and-doparallel-part-2"> R-exercises</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p><a rel="nofollow" href="https://i2.wp.com/www.r-exercises.com/wp-content/uploads/2017/07/parallel_2_foreach_2.png" target="_blank"><img alt="" src="https://i2.wp.com/www.r-exercises.com/wp-content/uploads/2017/07/parallel_2_foreach_2.png?resize=240%2C194" class="wp-image-6920" data-recalc-dims="1"></a></p>
<p>In general, <code>foreach</code> is a statement for iterating over items in a collection without using any explicit counter. In R, it is also a way to run code in parallel, which may be more convenient and readable that the <code>sfLapply</code> function (considered in the previous set of exercises of this series) or other <code>apply</code>-alike functions.<br>
Apart from being able to run code in parallel, the R’s <code>foreach</code> has some other differences from the standard <code>for</code> loop. Specifically, the <code>foreach</code> statement:</p>
<ul>
<li>allows to iterate over several variables simultaneously,</li>
<li>returns a value (a list, a vector, a matrix, or another object),</li>
<li>is able to skip some iterations based on a condition (the last two properties make it similar to the list comprehension, which is present in Python and some other languages), </li>
<li>has a special syntax that includes operators <code>%do%</code> (see an example in Exercise 1), <code>%dopar%</code>, and <code>%:%</code>.</li>
</ul>
<p>The first six exercises in this set allow to train in performing basic operations with the <code>foreach</code> statement, and the last four ones show how to run it in parallel using multiple CPU cores on one machine. The task will be to parallelize identical operations on a set of files (the zipped data files can be downloaded <a rel="nofollow" href="http://www.r-exercises.com/wp-content/uploads/2017/07/test_data_foreach.zip" target="_blank">here</a>). It is assumed that your computer has two or more CPU cores.<br>
The exercises require the packages <code>foreach</code>, <code>doParallel</code>, and <code>parallel</code>. The first two packages have to be installed, and the last one comes with the standard R distribution. The packages <code>doParallel</code> and <code>parallel</code> are necessary to run <code>foreach</code> in parallel.<br>
For other parts of the series follow the tag <a rel="nofollow" href="http://www.r-exercises.com/tags/parallel-computing" target="_blank">parallel computing</a>.<br>
Answers to the exercises are available <a rel="nofollow" href="http://r-exercises.com/2017/07/13/parallel-computing-exercises-foreach-and-doparallel-part-2-solutions" target="_blank">here</a>.</p>
<p><strong>Exercise 1</strong><br>
The <code>foreach</code> function (from the package of the same name) is typically used as a part of a special statement. In its simple form, the statement looks like this: </p>
<p align="center"><code>result &lt;- foreach(i = 1:3) %do% sqrt(i)</code></p>
<p>The statement above consists of three parts:</p>
<ul>
<li><code>foreach(i = 1:3)</code> – a call to the <code>foreach</code> function, with an argument that includes an iteration variable (<code>i</code>) and a sequence to be iterated over (<code>1:3</code>),</li>
<li><code>%do%</code> – a special operator,</li>
<li><code>sqrt(i)</code>: an R expression, which represents an operation to be performed over the iteration variable (this part of the statement is equivalent to the body of the loop).</li>
</ul>
<p>The code iterates over the sequence, applies an operation defined in the expression to each element of the sequence, and stores the output in the <code>result</code> variable.<br>
Note that if the expression extends over several lines it has to be enclosed in curly braces. The use of the iteration variable is not mandatory: if you just want to repeat the expression <code>n</code> times not passing anything to that expression you can use only a sequence of the length <code>n</code> as input to <code>foreach</code>.<br>
In this exercise:</p>
<ol>
<li>Run the code above, print the <code>result</code> object, and find to which class it belongs.</li>
<li>Use the <code>foreach</code> function to reverse the result. I.e. write a line of code that receives the <code>result</code> object as an input, and outputs the original sequence. Print the sequence.</li>
</ol>
<p><strong>Exercise 2</strong><br>
The <code>foreach</code> function allows for the use of several iteration variables simultaneously. They are passed to the function as arguments, and are separated by commas.<br>
Run the <code>foreach</code> function with two iteration variables to get a sequence of their sums. The variables have to iterate over a vector of integers from 1 to 3, and a vector of 5 integers of value 10. Print the result.<br>
(Tip: if you want to use an arithmetic operator to calculate the sum then the expression must be placed in parentheses or curly braces).<br>
What is the length of the resulting object? How does the function deal with the vectors of different length?</p>
<p><strong>Exercise 3</strong><br>
The package <code>iterators</code> provides several functions that can be used to create sequences for the <code>foreach</code> function. For example, the <code>irnorm</code> function creates an object that iterates over vectors of normally distributed random numbers. It is useful when you need to use random variables drawn from one distribution in an expression that is run in parallel.<br>
In this exercise, use the <code>foreach</code> and <code>irnorm</code> functions to iterate over 3 vectors, each containing 5 random variables. Find the largest value in each vector, and print those largest values.<br>
Before running the <code>foreach</code> function set the seed to 1234.</p>
<div>
<aside><img src="http://www.r-exercises.com/2017/07/13/parallel-computing-exercises-foreach-and-doparallel-part-2/?utm_source=rss&utm_medium=rss&utm_campaign=parallel-computing-exercises-foreach-and-doparallel-part-2"></aside>
<div><strong>Learn more</strong> about optimizing your workflow in the online course <a rel="nofollow" href="http://www.r-exercises.com/product/getting-started-with-r-for-data-science/" target="_blank">Getting Started with R for Data Science</a>. In this course you will learn how to:
<ul>
<li>efficiently organize your workflow to get the best performance of your entire project</li>
<li>get a full introduction to using R for a data science project</li>
<li>And much more</li>
</ul>
</div>
</div>
<p><strong>Exercise 4</strong><br>
By default the <code>foreach</code> function returns a list. But it can also return sequences of other types. This requires changing the value of the <code>.combine</code> parameter of the function. This exercise will train how to use this parameter.<br>
As in the previous exercise, use the <code>foreach</code> and <code>irnorm</code> functions to iterate over 3 vectors, each containing 5 random variables. But now use an expression that returns all variables generated by <code>irnorm</code>. Pass the <code>.combine</code> parameter to the <code>foreach</code> function with value <code>'c'</code>. Print the result, and find its class and length.<br>
Then run the code again with the <code>'cbind'</code> value assigned to the <code>.combine</code> parameter. Print the result, find its class and size.<br>
Note that <code>'c'</code> and <code>'cbind'</code> are R functions from the <code>base</code> package. Other functions (including user-written ones) can be used as well to combine the outputs of the expression.</p>
<p><strong>Exercise 5</strong><br>
The results of the expression placed after the <code>%do%</code> operator can be combined in different ways. Look at the documentation for the <code>foreach</code> function to find what value has to be assigned to the <code>.combine</code> parameter to sum the values produced by the expression in each iteration.<br>
Run the code used in previous exercise with that value assigned to the <code>.combine</code> parameter, and print the result.<br>
Before running the code set the seed to 1234.</p>
<p><strong>Exercise 6</strong><br>
The sequence passed to the <code>foreach</code> function can be filtered so that the expression after <code>%do%</code> is applied only to a part of the sequence. This is done using a syntax like this:</p>
<p align="center"><code>result ‹- foreach(i = some_sequence) %:% when(i › 0) %do% sqrt(i)</code></p>
<p>You can notice that the <code>%:%</code> operator and the <code>when</code> function, which contains a Boolean expression involving the iteration variable, are added to a standard <code>foreach</code> statement.<br>
Modify the example above to get a vector of logs of all even integers in the range from 1 to 10. Print the result.</p>
<p><strong>Exercise 7</strong><br>
Now let’s parallelize the execution of the <code>foreach</code> function. We’ll use it to read similarly named files, and perform identical calculations on data from each file.<br>
As a first step, write a function to be run in parallel. The function takes an integer as input, and performs the following actions:</p>
<ol>
<li>Create a string (character vector) with a file name by concatenating constant parts of the name (<code>test_data_</code>, <code>.csv</code>) with the integer (example of possible result when 1 is used as integer: <code>test_data_1.csv</code>).</li>
<li>Read the file with the obtained name from the current working directory into a data frame.</li>
<li>Calculate mean values for each column in the data frame.</li>
<li>Return a vector of those values.</li>
</ol>
<p><strong>Exercise 8</strong><br>
The second step is to create a backend for parallel execution:</p>
<ol>
<li>Make a cluster for parallel execution using the <code>makeCluster</code> function from the <code>parallel</code> package; pass the size of the cluster (i.e. the number of CPU cores that you want to be used in computations) as an argument to this function .</li>
<li>Register the cluster with the <code>registerDoParallel</code> function from the <code>doParallel</code> package.</li>
</ol>
<p>Note that by default the <code>makeCluster</code> function creates a <code>PSOCK</code> cluster, which is an enhanced version of the <code>SOCK</code> cluster implemented in the <code>snow</code> package. Accordingly, the <code>PSOCK</code> cluster is a pool of worker processes that exchange data with the master process via sockets. The <code>makeCluster</code> function can also create other types of clusters.</p>
<p><strong>Exercise 9</strong><br>
The last step is to run the <code>foreach</code> function to read and analyze 10 test files (contained in <a rel="nofollow" href="http://www.r-exercises.com/wp-content/uploads/2017/07/test_data_foreach.zip" target="_blank">this</a> archive) using the function created in Exercise 7. Combine the outputs of that function using <code>rbind</code>.<br>
Perform this task twice:</p>
<ol>
<li>with <code>%do%</code> operator, which evaluates the expression sequentially, and</li>
<li>with <code>%dopar%</code> operator, which evaluates the expression in parallel.</li>
</ol>
<p>In both cases, measure the execution time using the the <code>system.time</code> function. Print the result of the last run.<br>
IMPORTANT: after completing parallel computations stop the cluster (created in Exercise 8) using the <code>stopCluster</code> function from the <code>parallel</code> package.</p>
<p><strong>Exercise 10</strong><br>
Modify the code written in the Exercise 7 and Exercise 9 to calculate the mean and the variance of values contained in the first column in each file. The resulting object must be a two-column matrix with the first column representing means, and the second column describing variances (the number of rows must be equal to the number of files).<br>
Repeat the actions listed in Exercise 8 to prepare a cluster for parallel execution, then run the modified code in parallel.<br>
Print the result.<br>
Stop the cluster.</p>
<div>
<h3>Related exercise sets:</h3>
<ol>
<li><a rel="nofollow" href="http://www.r-exercises.com/2017/07/06/parallel-computing-exercises-snowfall-part-1/" title="Parallel Computing Exercises: Snowfall (Part-1)" target="_blank">Parallel Computing Exercises: Snowfall (Part-1) </a></li>
<li><a rel="nofollow" href="http://www.r-exercises.com/2015/12/31/list-exercises/" title="List exercises" target="_blank">List exercises </a></li>
<li><a rel="nofollow" href="http://www.r-exercises.com/2016/12/27/list-exercises-vol-2/" title="List Vol.2 Exercises" target="_blank">List Vol.2 Exercises </a></li>
<li><a rel="nofollow" href="http://www.r-exercises.com/start-here-to-learn-r/" target="_blank">Explore all our (>1000) R exercises</a></li>
<li><a rel="nofollow" href="http://www.r-exercises.com/r-courses/" target="_blank">Find an R course using our R Course Finder</a> directory</li>
</ol>
</div>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://www.r-exercises.com/2017/07/13/parallel-computing-exercises-foreach-and-doparallel-part-2/?utm_source=rss&utm_medium=rss&utm_campaign=parallel-computing-exercises-foreach-and-doparallel-part-2"> R-exercises</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/6NLY-6lwBU0" height="1"></a></div>