如果有人能给我一些指导如何解决矩阵的复杂排序和选择每个子类别中的前 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 行的选择。
任何想法或代码将不胜感激。
谢谢