Get Started

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"

The correlation matrix, corr, is available for you to use.

This is a part of the course

“Intermediate R for Finance”

View Course

Exercise instructions

  • 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.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# 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]))
    }
}
Edit and Run Code

This exercise is part of the course

Intermediate R for Finance

BeginnerSkill Level
4.7+
11 reviews

Learn about how dates work in R, and explore the world of if statements, loops, and functions using financial examples.

Loops can be useful for doing the same operation to each element of your data structure. In this chapter you will learn all about repeat, while, and for loops!

Exercise 1: Repeat loopsExercise 2: Repeat, repeat, repeatExercise 3: When to break?Exercise 4: While loopsExercise 5: While with a printExercise 6: While with a plotExercise 7: Break itExercise 8: For loopsExercise 9: Loop over a vectorExercise 10: Loop over data frame rowsExercise 11: Loop over matrix elements
Exercise 12: Break and next

What is DataCamp?

Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.

Start Learning for Free