Перейти к основному содержимому

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.
· 5 мин читать

Исследуйте с ИИ


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.


# Sequence
         seq <- c(1:10)

         # Print loop
         for (value in ___) {
           print(___)
         }

          # A sum variable
          sum <- 0

          # Sum loop
          for (value in seq) {
          sum <- ___ + ___
          print(___)
          }

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 an important day!

# Loop over stock rows
         for (row in 1:___) {
              price <- stock[___, "___"]
              date  <- stock[___, "___"]

              if(___ > ___) {
                  print(paste("On", ___,
                              "the stock price was", ___))
              } else {
                  print(paste("The date:, ___,
                              "is not an important day!"))
              }
            }

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.

  # Print out corr


        # Create a nested loop
        for(row in 1:nrow(___)) {
            for(col in 1:___(corr)) {
                print(paste(colnames(corr)[___], "and", rownames(corr)[___],
                            "have a correlation of", corr[row,col]))
            }
        }

Also check out our A Loops in R Tutorial.

Темы

Связанное

Учебное руководство

A Loops in R Tutorial - Usage and Alternatives

Учебное руководство

For Loops in Python Tutorial