行列の複雑な順序付けと各サブカテゴリの上位 2 つの要素の選択を解決する方法について、誰かが私に指示を与えることができれば幸いです。
コード:
index<-1:14
metric<-c(0.037777,0.041143,0.041043,0.042056,0.043701,0.042169,0.042134,
0.046565,0.044638,0.036653,0.046221,0.04033,0.045385,0.043873)
cat_1<-c("California Munis","California Munis","California Munis","California Munis",
"California Munis","California Munis","California Munis","Corporate Bonds",
"Corporate Bonds","Corporate Bonds","Government Bonds","Government Bonds",
"High Yield Bonds","High Yield Bonds")
cat_2<-c("California Munis","Corporate Bonds","Corporate Bonds","Government Bonds",
"High Yield Bonds","High Yield Bonds","High Yield Bonds","High Yield Bonds",
"High Yield Bonds","High Yield Bonds","California Munis","California Munis",
"Corporate Bonds","Corporate Bonds")
data<-data.frame(cbind(index,metric,cat_1,cat_2))
以下の行列を生成します
Ind Metric Cat_1 Cat_2
1 0.037777 California Munis California Munis
2 0.041143 California Munis Corporate Bonds
3 0.041043 California Munis Corporate Bonds
4 0.042056 California Munis Government Bonds
5 0.043701 California Munis High Yield Bonds
6 0.042169 California Munis High Yield Bonds
7 0.042134 California Munis High Yield Bonds
8 0.046565 Corporate Bonds High Yield Bonds
9 0.044638 Corporate Bonds High Yield Bonds
10 0.036653 Corporate Bonds High Yield Bonds
11 0.046221 Government Bonds California Munis
12 0.04033 Government Bonds California Munis
13 0.045385 High Yield Bonds Corporate Bonds
14 0.043873 High Yield Bonds Corporate Bonds
上記のマトリックスから、Cat_1、Cat_2、Metric に基づいて注文したいと思います。私はこれを試しました:
data[order(data[,3],data[,4],data[,2]),]
ただし、エントリが同じ場合、Cat_1 と Cat_2 は区別されません。例として、"California Munis"&"Corporate Bonds"="Corporate Bonds"&"California Munis". 私が取得しようとしている結果は、次のマトリックスの結果のようになります
Ind Metric Cat_1 Cat_2 Selection
1 0.037777 California Munis California Munis 1
2 0.041143 California Munis Corporate Bonds 1
3 0.041043 California Munis Corporate Bonds 2
11 0.046221 Government Bonds California Munis 1
4 0.042056 California Munis Government Bonds 2
12 0.04033 Government Bonds California Munis
5 0.043701 California Munis High Yield Bonds 1
6 0.042169 California Munis High Yield Bonds 2
7 0.042134 California Munis High Yield Bonds
8 0.046565 Corporate Bonds High Yield Bonds 1
13 0.045385 High Yield Bonds Corporate Bonds 2
9 0.044638 Corporate Bonds High Yield Bonds
14 0.043873 High Yield Bonds Corporate Bonds
10 0.036653 Corporate Bonds High Yield Bonds
最後の列は、抽出する必要があるすべてのサブカテゴリごとに上位 2 行の選択を示しています。
どんなアイデアやコードでも大歓迎です。
ありがとう