Skip to main content

For Loops in R

When you know how many times you want to repeat an action, a for loop is a good option. Master for loops with this tutorial.
Sep 26, 2018  · 5 min read


Master for loops and other essential R functions with our introduction to R course.

Loop over a Vector

When you know how many times you want to repeat an action, a for loop is a good option. The idea of the for loop is that you are stepping through a sequence, one at a time, and performing an action at each step along the way. That sequence is commonly a vector of numbers (such as the sequence from 1:10), but could also be numbers that are not in any order like c(2, 5, 4, 6), or even a sequence of characters!

for (value in sequence) {
    code
}

In words this is saying, "for each value in my sequence, run this code." Examples could be, "for each row of my data frame, print column 1", or "for each word in my sentence, check if that word is DataCamp."

Let's try an example! First, you will create a loop that prints out the values in a sequence from 1 to 10. Then, you will modify that loop to also sum the values from 1 to 10, where at each iteration the next value in the sequence is added to the running sum.

Instructions

A vector seq has been created for you. Fill in the for loop, using seq as your sequence. Print out value during each iteration. A variable sum has been created for you. Use the loop to sum the numbers in seq. Each iteration, value should be added to sum, then sum is printed out.

eyJsYW5ndWFnZSI6InIgIiwicHJlX2V4ZXJjaXNlX2NvZGUiOiJcbiIsInNh bXBsZSI6IlxuIyBTZXF1ZW5jZVxuICAgICAgICAgc2VxIDwtIGMoMToxMClc blxuICAgICAgICAgIyBQcmludCBsb29wXG4gICAgICAgICBmb3IgKHZhbHVl IGluIF9fXykge1xuICAgICAgICAgICBwcmludChfX18pXG4gICAgICAgICB9 XG5cbiAgICAgICAgICAjIEEgc3VtIHZhcmlhYmxlXG4gICAgICAgICAgc3Vt IDwtIDBcblxuICAgICAgICAgICMgU3VtIGxvb3BcbiAgICAgICAgICBmb3Ig KHZhbHVlIGluIHNlcSkge1xuICAgICAgICAgIHN1bSA8LSBfX18gKyBfX19c biAgICAgICAgICBwcmludChfX18pXG4gICAgICAgICAgfSIsInNvbHV0aW9u IjoiXG4jIFNlcXVlbmNlXG4gICAgICAgICAgc2VxIDwtIGMoMToxMClcblxu ICAgICAgICAgICMgUHJpbnQgbG9vcFxuICAgICAgICAgIGZvciAodmFsdWUg aW4gc2VxKSB7XG4gICAgICAgICAgICAgIHByaW50KHZhbHVlKVxuICAgICAg ICAgIH1cblxuICAgICAgICAgICMgQSBzdW0gdmFyaWFibGVcbiAgICAgICAg ICBzdW0gPC0gMFxuXG4gICAgICAgICAgIyBTdW0gbG9vcFxuICAgICAgICAg IGZvciAodmFsdWUgaW4gc2VxKSB7XG4gICAgICAgICAgICAgIHN1bSA8LSBz dW0gKyB2YWx1ZVxuICAgICAgICAgICAgICBwcmludChzdW0pXG4gICAgICAg ICAgfSIsInNjdCI6IlxudGVzdF9wcmVkZWZpbmVkX29iamVjdHMoXCJzZXFc IilcblxuICAgICAgICAgIHRlc3RfZm9yX2xvb3AoY29uZF90ZXN0ID0gdGVz dF9zdHVkZW50X3R5cGVkKFwidmFsdWUgaW4gc2VxXCIpLFxuICAgICAgICAg ICAgICAgICAgZXhwcl90ZXN0ID0gdGVzdF9mdW5jdGlvbihcInByaW50XCIs IGFyZ3MgPSBcInhcIiksXG4gICAgICAgICAgICAgICAgICBpbmRleCA9IDEp XG5cbiAgICAgICAgICB0ZXN0X2Zvcl9sb29wKGNvbmRfdGVzdCA9IHRlc3Rf c3R1ZGVudF90eXBlZChcInZhbHVlIGluIHNlcVwiKSxcbiAgICAgICAgICAg ICAgICAgICAgICBleHByX3Rlc3QgPSB0ZXN0X2NvcnJlY3QodGVzdF9mdW5j dGlvbihcInByaW50XCIsIGFyZ3MgPSBcInhcIiksIHsgIyBJZiB0aGUgcHJp bnQgc3RhdGVtZW50IGlzIHdyb25nLCB0aGVuIGNoZWNrIHRoZSBhc3NpZ25t ZW50XG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg dGVzdF9vcih0ZXN0X3N0dWRlbnRfdHlwZWQoXCJzdW0gKyB2YWx1ZVwiKSwg IyBEaWQgdGhleSBhc3NpZ24gdGhpcyBjb3JyZWN0bHk/XG4gICAgICAgICAg ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICB0ZXN0X3N0 dWRlbnRfdHlwZWQoXCJ2YWx1ZSArIHN1bVwiKVxuICAgICAgICAgICAgICAg ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgKVxuICAgICAgICAg ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgfSksXG4gICAgICAgICAg ICAgICAgICAgICAgICBpbmRleCA9IDIpXG5cbiAgICAgICAgICAgIHN1Y2Nl c3NfbXNnKFwiR3JlYXQgam9iISBMZXQncyBzZWUgd2hhdCBlbHNlIHlvdSBj YW4gZG8gd2l0aCBmb3IgbG9vcHMuXCIpIiwiaGludCI6IlxuLSBJbiB0aGUg Zmlyc3QgbG9vcCwgcmVtZW1iZXIgd2hhdCB5b3VyIHNlcXVlbmNlIHNob3Vs ZCBiZS5cbiAgICAgICAgICAgICAgICAgIC0gSW4gdGhlIHNlY29uZCBsb29w LCB5b3UgaGF2ZSB0byBhZGQgYHZhbHVlYCB0byBgc3VtYCBhbmQgdGhlbiBh c3NpZ24gdGhhdCB2YWx1ZSBiYWNrIHRvIGBzdW1gLiJ9

If that makes sense keep going to the next exercise! If not, here is an overview video.

Overview Video on For Loops in R

Loop over Data Frame Rows

Imagine that you are interested in the days where the stock price of Apple rises above 117. If it goes above this value, you want to print out the current date and stock price. If you have a stock data frame with a date and apple price column, could you loop over the rows of the data frame to accomplish this? You certainly could!

Before you do so, note that you can get the number of rows in your data frame using nrow(stock). Then, you can create a sequence to loop over from 1:nrow(stock).

for (row in 1:nrow(stock)) {
    price <- stock[row, "apple"]
    date  <- stock[row, "date"]

    if(price > 117) {
        print(paste("On", date,
                    "the stock price was", price))
    }
}
[1] "On 2016-12-21 the stock price was 117.06"
[1] "On 2016-12-27 the stock price was 117.26"

This incorporates a number of things we have learned so far. If statements, subsetting vectors, conditionals, and loops! Congratulations for learning so much!

Instructions

stock is in your workspace.

Fill in the blanks in the for loop to make the following true:

  • price should hold that iteration's price
  • date should hold that iteration's date
  • This time, you want to know if apple goes above 116.
  • If it does, print the date and price.
  • If it was below 116, print out the date and print that it was not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gICAgICAgICAgIDExNS4xOSwgMTE1LjgyLCAxMTUuOTcsIE5BLCBOQSwg MTE2LjY0LCAxMTYuOTUsIDExNy4wNiwgMTE2LjI5LCAxMTYuNTIsIE5BLCBO QSwgMTE3LjI2LFxuICAgICAgICAgICAgICAgICAgICAgICAgMTE2Ljc2LCAx MTYuNzMsIDExNS44MilcbiAgICAgICAgICApXG4gICAgICAgICAgc3RvY2sg PC0gc3Vic2V0KHN0b2NrLCAhaXMubmEoYXBwbGUpKSIsInNhbXBsZSI6Ilxu IyBMb29wIG92ZXIgc3RvY2sgcm93c1xuICAgICAgICAgZm9yIChyb3cgaW4g MTpfX18pIHtcbiAgICAgICAgICAgICAgcHJpY2UgPC0gc3RvY2tbX19fLCBc Il9fX1wiXVxuICAgICAgICAgICAgICBkYXRlICA8LSBzdG9ja1tfX18sIFwi X19fXCJdXG5cbiAgICAgICAgICAgICAgaWYoX19fID4gX19fKSB7XG4gICAg ICAgICAgICAgICAgICBwcmludChwYXN0ZShcIk9uXCIsIF9fXyxcbiAgICAg ICAgICAgICAgICAgICAgICAgICAgICAgIFwidGhlIHN0b2NrIHByaWNlIHdh c1wiLCBfX18pKVxuICAgICAgICAgICAgICB9IGVsc2Uge1xuICAgICAgICAg ICAgICAgICAgcHJpbnQocGFzdGUoXCJUaGUgZGF0ZTosIF9fXyxcbiAgICAg ICAgICAgICAgICAgICAgICAgICAgICAgIFwiaXMgbm90IGFuIGltcG9ydGFu dCBkYXkhXCIpKVxuICAgICAgICAgICAgICB9XG4gICAgICAgICAgICB9Iiwi c29sdXRpb24iOiJcbiMgTG9vcCBvdmVyIHN0b2NrIHJvd3NcbiAgICAgICAg ICBmb3IgKHJvdyBpbiAxOm5yb3coc3RvY2spKSB7XG4gICAgICAgICAgICAg IHByaWNlIDwtIHN0b2NrW3JvdywgXCJhcHBsZVwiXVxuICAgICAgICAgICAg ICBkYXRlICA8LSBzdG9ja1tyb3csIFwiZGF0ZVwiXVxuXG4gICAgICAgICAg ICAgIGlmKHByaWNlID4gMTE2KSB7XG4gICAgICAgICAgICAgICAgICBwcmlu dChwYXN0ZShcIk9uXCIsIGRhdGUsXG4gICAgICAgICAgICAgICAgICAgICAg ICAgICAgICBcInRoZSBzdG9jayBwcmljZSB3YXNcIiwgcHJpY2UpKVxuICAg ICAgICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgICAgICAgICAgcHJpbnQo cGFzdGUoXCJUaGUgZGF0ZTpcIiwgZGF0ZSxcbiAgICAgICAgICAgICAgICAg ICAgICAgICAgICAgIFwiaXMgbm90IGFuIGltcG9ydGFudCBkYXkhXCIpKVxu ICAgICAgICAgICAgICB9XG4gICAgICAgICAgICB9Iiwic2N0IjoiXG50ZXN0 X3ByZWRlZmluZWRfb2JqZWN0cyhcInN0b2NrXCIpXG5cbiAgICAgICAgICB0 ZXN0X2Zvcl9sb29wKGNvbmRfdGVzdCA9IHRlc3Rfc3R1ZGVudF90eXBlZChc InJvdyBpbiAxOm5yb3coc3RvY2spXCIpLFxuICAgICAgICAgICAgICAgICAg ICAgICAgZXhwcl90ZXN0ID0gdGVzdF9pZl9lbHNlKGlmX2NvbmRfdGVzdCAg ID0gdGVzdF9zdHVkZW50X3R5cGVkKFwicHJpY2UgPiAxMTZcIiksXG4gICAg ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBp Zl9leHByX3Rlc3QgICA9IHRlc3RfZnVuY3Rpb24oXCJwcmludFwiLCBhcmdz ID0gXCJ4XCIsIGluY29ycmVjdF9tc2cgPSBcIlRoZSBwcmludCBzdGF0ZW1l bnQgb3V0cHV0IGlzIGluY29ycmVjdCwgYXJlIGBkYXRlYCBhbmQgYHByaWNl YCBkZWZpbmVkIGNvcnJlY3RseT9cIiksXG5cbiAgICAgICAgICAgICAgICAg ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIGVsc2VfZXhwcl90ZXN0 ID0gdGVzdF9mdW5jdGlvbihcInByaW50XCIsIGFyZ3MgPSBcInhcIikpXG4g ICAgICAgICAgICAgICAgICAgICAgICApXG5cbiAgICAgICAgICBzdWNjZXNz X21zZyhcIk5pY2Ugam9iIVwiKSIsImhpbnQiOiJcbi0gVGhlIGJsYW5rcyB5 b3UgZmlsbCBpbiBzaG91bGQgYmUgc2ltaWxhciB0byB0aGUgZXhhbXBsZS5c biAgICAgICAgICAgICAgICAtIEZvciB0aGUgZWxzZSBzdGF0ZW1lbnQgYmxh bmtzLCB5b3UgbmVlZCB0byBzZWxlY3QgdGhlIGBkYXRlYCBmb3IgdGhlIGN1 cnJlbnQgcm93LiJ9

Loop over Matrix Elements

So far, you have been looping over 1 dimensional data types. If you want to loop over elements in a matrix (columns and rows), then you will have to use nested loops. You will use this idea to print out the correlations between three stocks.

The easiest way to think about this is that you are going to start on row1, and move to the right, hitting col1, col2, ..., up until the last column in row1. Then, you move down to row2 and repeat the process.

my_matrix
     [,1]   [,2]  
[1,] "r1c1" "r1c2"
[2,] "r2c1" "r2c2"

# Loop over my_matrix
for(row in 1:nrow(my_matrix)) {
    for(col in 1:ncol(my_matrix)) {
        print(my_matrix[row, col])
    }
}
[1] "r1c1"
[1] "r1c2"
[1] "r2c1"
[1] "r2c2"

Instructions

The correlation matrix, corr, is in your workspace.

  • Print corr to get a peek at the data.
  • Fill in the nested for loop! It should satisfy the following:
    • The outer loop should be over the rows of corr.
    • The inner loop should be over the cols of corr.
    • The print statement should print the names of the current column and row, and also print their correlation.
eyJsYW5ndWFnZSI6InIgIiwicHJlX2V4ZXJjaXNlX2NvZGUiOiJcbnN0b2Nr cyA8LSBjKFwiYXBwbGVcIiwgXCJpYm1cIiwgXCJtaWNyXCIpXG4gICAgICAg IGNvcnIgPC0gbWF0cml4KGMoMSwgLjk2LCAuODgsIC45NiwgMSwgLjc0LCAu ODgsIC43NCwgMSksIG5yb3c9MylcblxuICAgICAgICBjb2xuYW1lcyhjb3Jy KSA8LSBzdG9ja3NcbiAgICAgICAgcm93bmFtZXMoY29ycikgPC0gc3RvY2tz Iiwic2FtcGxlIjoiXG4gICMgUHJpbnQgb3V0IGNvcnJcblxuXG4gICAgICAg ICMgQ3JlYXRlIGEgbmVzdGVkIGxvb3BcbiAgICAgICAgZm9yKHJvdyBpbiAx Om5yb3coX19fKSkge1xuICAgICAgICAgICAgZm9yKGNvbCBpbiAxOl9fXyhj b3JyKSkge1xuICAgICAgICAgICAgICAgIHByaW50KHBhc3RlKGNvbG5hbWVz KGNvcnIpW19fX10sIFwiYW5kXCIsIHJvd25hbWVzKGNvcnIpW19fX10sXG4g ICAgICAgICAgICAgICAgICAgICAgICAgICAgXCJoYXZlIGEgY29ycmVsYXRp b24gb2ZcIiwgY29ycltyb3csY29sXSkpXG4gICAgICAgICAgICB9XG4gICAg ICAgIH0iLCJzb2x1dGlvbiI6IlxuICAjIFByaW50IG91dCBjb3JyXG4gICAg ICAgICAgY29yclxuXG4gICAgICAgICAgIyBDcmVhdGUgYSBuZXN0ZWQgbG9v cFxuICAgICAgICAgIGZvcihyb3cgaW4gMTpucm93KGNvcnIpKSB7XG4gICAg ICAgICAgICAgIGZvcihjb2wgaW4gMTpuY29sKGNvcnIpKSB7XG4gICAgICAg ICAgICAgICAgICBwcmludChwYXN0ZShjb2xuYW1lcyhjb3JyKVtjb2xdLCBc ImFuZFwiLCByb3duYW1lcyhjb3JyKVtyb3ddLFxuICAgICAgICAgICAgICAg ICAgICAgICAgICAgICAgXCJoYXZlIGEgY29ycmVsYXRpb24gb2ZcIiwgY29y cltyb3csY29sXSkpXG4gICAgICAgICAgICAgIH1cbiAgICAgICAgICB9Iiwi c2N0IjoiXG50ZXN0X2Zvcl9sb29wKGNvbmRfdGVzdCA9IHRlc3Rfc3R1ZGVu dF90eXBlZChcInJvdyBpbiAxOm5yb3coY29ycilcIiksXG4gICAgICAgICAg ICAgICAgICAgICAgICBleHByX3Rlc3QgPSB0ZXN0X2Zvcl9sb29wKGNvbmRf dGVzdCAgID0gdGVzdF9zdHVkZW50X3R5cGVkKFwiY29sIGluIDE6bmNvbChj b3JyKVwiKSxcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg ICAgICAgICAgICAgICAgZXhwcl90ZXN0ICAgPSB0ZXN0X2Z1bmN0aW9uKFwi cHJpbnRcIiwgYXJncyA9IFwieFwiLCBpbmNvcnJlY3RfbXNnID0gXCJUaGUg cHJpbnQgc3RhdGVtZW50IG91dHB1dCBpcyBpbmNvcnJlY3QsIGRpZCB5b3Ug ZmlsbCBpbiBgY29sYCBhbmQgYHJvd2AgZm9yIHRoZSBibGFua3M/XCIpXG4g ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg ICAgIClcbiAgICAgICAgICAgICAgICAgICAgICAgIClcblxuICAgICAgICAg ICBzdWNjZXNzX21zZyhcIk5pY2UhIFRoYXQgd2FzIGEgdG91Z2ggb25lLiBO ZXN0ZWQgbG9vcHMgcmVxdWlyZSBhIGxvdCBvZiBjb21wdXRhdGlvbmFsIGVu ZXJneSwgYmVjYXVzZSBzbyBtYW55IGNhbGN1bGF0aW9ucyBhcmUgcmVxdWly ZWQuXCIpIiwiaGludCI6IlxuICAtIERvbid0IGZvcmdldCB0byB1c2UgdGhl IGBucm93KClgIGFuZCBgbmNvbCgpYCBmdW5jdGlvbnMgaW4geW91ciBsb29w LlxuICAgICAgICAgICAgICAgICAgLSBUaGUgY29kZSB1c2VkIHRvIGNyZWF0 ZSB0aGUgc3RydWN0dXJlIG9mIHRoZSBsb29wIHNob3VsZCBiZSB0aGUgc2Ft ZSBhcyB0aGUgZXhhbXBsZS4ifQ==

Also check out our A Loops in R Tutorial.

Topics

Learn more about R

course

Intermediate R

6 hr
598.5K
Continue your journey to becoming an R ninja by learning about conditional statements, loops, and vector functions.
See DetailsRight Arrow
Start Course
See MoreRight Arrow
Related

tutorial

A Loops in R Tutorial - Usage and Alternatives

A tutorial on loops in R that looks at the constructs available in R for looping. Discover alternatives using R's vectorization feature.
Carlo Fanara's photo

Carlo Fanara

32 min

tutorial

For Loops in Python Tutorial

Learn how to implement For Loops in Python for iterating a sequence, or the rows and columns of a pandas dataframe.
Aditya Sharma's photo

Aditya Sharma

5 min

tutorial

A Beginner's Guide to Python for Loops: Mastering for i in range

In the realm of Python programming, mastering loops is crucial. This tutorial sheds light on the Python for i in range loop, a fundamental construct in Python.
Abid Ali Awan's photo

Abid Ali Awan

5 min

tutorial

Python Loops Tutorial

A comprehensive introductory tutorial to Python loops. Learn and practice while and for loops, nested loops, the break and continue keywords, the range function and more!
Satyabrata Pal's photo

Satyabrata Pal

22 min

tutorial

Utilities in R Tutorial

Learn about several useful functions for data structure manipulation, nested-lists, regular expressions, and working with times and dates in the R programming language.
Aditya Sharma's photo

Aditya Sharma

18 min

tutorial

Multiple Linear Regression in R: Tutorial With Examples

A complete overview to understanding multiple linear regressions in R through examples.
Zoumana Keita 's photo

Zoumana Keita

12 min

See MoreSee More