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