開始使用免費開始

函式中的函式

為了讓程式碼更乾淨,有時會在一個函式裡使用另一個函式。這樣你就能把前一個函式的結果直接當作下一個函式的輸入,而不必先建立中間變數。其實你已經看過 print() 搭配 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() 會把字元向量接在一起,而 print() 會把結果印到主控台。

下面的練習要用巢狀函式來簡化相關係數矩陣的計算。你可以使用 3 個股價向量:appleibmmicr

本練習屬於課程

R 金融中級

檢視課程

練習說明

  • 先用 cbind() 依序把 appleibmmicr 合併起來,並存成 stocks
  • 接著,對 stocks 使用 cor()
  • 現在試試一次完成:在 cor() 裡面直接使用 cbind(),用相同順序放入這 3 個股價向量,建立相關係數矩陣。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# cbind() the stocks
stocks <- ___

# cor() to create the correlation matrix
___

# All at once! Nest cbind() inside of cor()
___
編輯並執行程式碼