ComeçarComece de graça

Functions in functions

To write clean code, sometimes it is useful to use functions inside of other functions. This let's you use the result of one function directly in another one, without having to create an intermediate variable. You have actually already seen an example of this with print() and paste().

company <- c("Goldman Sachs", "J.P. Morgan", "Fidelity Investments")

for(i in 1:3) {
    print(paste("A large financial institution is", company[i]))
}
[1] "A large financial institution is Goldman Sachs"
[1] "A large financial institution is J.P. Morgan"
[1] "A large financial institution is Fidelity Investments"

paste() strings together the character vectors, and print() prints it to the console.

The exercise below explores simplifying the calculation of the correlation matrix using nested functions. Three vectors of stock prices, apple, ibm, and micr, are available for you to use.

Este exercício faz parte do curso

Intermediate R for Finance

Ver curso

Instruções do exercício

  • First, cbind() them together in the order of apple, ibm, micr. Save this as stocks.
  • Then, use cor() on stocks.
  • Now, let's see how this would work all at once. Use cbind() inside of cor() with the 3 stock vectors in the same order as above to create the correlation matrix.

Exercício interativo prático

Experimente este exercício completando este código de exemplo.

# cbind() the stocks
stocks <- ___

# cor() to create the correlation matrix
___

# All at once! Nest cbind() inside of cor()
___
Editar e executar o código