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.
Este exercício faz parte do curso
Intermediate R for Finance
Instruções do exercício
- 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
row
s ofcorr
. - The inner loop should be over the
col
s ofcorr
. - The print statement should print the names of the current column and row, and also print their correlation.
- The outer loop should be over the
Exercício interativo prático
Experimente este exercício completando este código de exemplo.
# 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]))
}
}