属性 (Attributes)
ついにコース最後の演習まで来ました。おめでとうございます!最後はやさしめの問題で締めくくりましょう。
属性は、データ構造に付随する追加のメタデータです。よく使われる属性には、行名・列名、次元、クラスなどがあります。attributes() 関数を使うと、渡したオブジェクトに関する属性の一覧(リスト)を取得できます。特定の属性にアクセスするには、attr() 関数を使用します。
cash の属性を見てみましょう:
attributes(cash)
$names
[1] "company" "cash_flow" "year"
$row.names
[1] 1 2 3 4 5 6 7
$class
[1] "data.frame"
attr(cash, which = "names")
[1] "company" "cash_flow" "year"
この演習はコースの一部です
金融のためのR入門
演習の手順
- 行列
my_matrixと因子my_factorはあらかじめ用意されています。 my_matrixに対してattributes()を使ってください。my_matrixに対してattr()を使い、"dim"属性を取得してください。my_factorに対してattributes()を使ってください。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
# my_matrix and my_factor
my_matrix <- matrix(c(1,2,3,4,5,6), nrow = 2, ncol = 3)
rownames(my_matrix) <- c("Row1", "Row2")
colnames(my_matrix) <- c("Col1", "Col2", "Col3")
my_factor <- factor(c("A", "A", "B"), ordered = T, levels = c("A", "B"))
# attributes of my_matrix
# Just the dim attribute of my_matrix
# attributes of my_factor