始める無料で始める

関数の中で関数を使う

読みやすいコードにするために、他の関数の中で関数を使うと便利なことがあります。これにより、ある関数の結果を中間変数を作らずに、そのまま別の関数に渡せます。実は、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() はその結果をコンソールに表示します。

次の演習では、入れ子の関数を使って相関行列の計算を簡潔にする方法を見ていきます。株価ベクトル appleibmmicr の 3 つが用意されています。

この演習はコースの一部です

金融のための中級R

コースを見る

演習の手順

  • まず、appleibmmicr の順で cbind() し、stocks として保存します。
  • 次に、stocks に対して cor() を使います。
  • では、これを一度に行う方法を試しましょう。上と同じ順序で 3 つの株価ベクトルを cbind() し、それを cor() の中で使って相関行列を作成します。

実践的なインタラクティブ演習

このサンプルコードを完成させて、この演習に挑戦してみましょう。

# cbind() the stocks
stocks <- ___

# cor() to create the correlation matrix
___

# All at once! Nest cbind() inside of cor()
___
コードを編集して実行