BaşlayınÜcretsiz Başlayın

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.

Bu egzersiz

Intermediate R for Finance

kursunun bir parçasıdır
Kursu Görüntüle

Egzersiz talimatları

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

Uygulamalı interaktif egzersiz

Bu örnek kodu tamamlayarak bu egzersizi bitirin.

# cbind() the stocks
stocks <- ___

# cor() to create the correlation matrix
___

# All at once! Nest cbind() inside of cor()
___
Kodu Düzenle ve Çalıştır