我正在尝试对订单股票进行排名(例如返回)。因此,我希望收到一个表格,其中包含按升序/降序排列的股票名称(此等级顺序函数的参数),并正确处理NAs(在每行末尾移动)。我真的无法想出一个优雅的方法来做到这一点。
下面是我想要的一个例子:
这是xts对象的coredata,表示不同时间的某些属性:
john joe tina jack suzie sasha sven luca
2003-05-29 1 2 3 4 5 6 7 8
2003-06-27 2 3 4 5 6 7 8 1
2003-07-30 3 4 5 6 7 8 1 2
2003-07-31 NA 2 3 4 5 6 1 NA
我需要一个数据框,每行(每个日期)显示第1列最佳排名(基于属性)的先前数据框中的列名,第2列中第二最佳,...请注意最后一行我需要将NAs移到最后(最后两列)或跳过...
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
2003-05-29 "john" "joe" "tina" "jack" "suzie" "sasha" "sven" "luca"
2003-06-27 "luca" "john" "joe" "tina" "jack" "suzie" "sasha" "sven"
2003-07-30 "sven" "luca" "john" "joe" "tina" "jack" "suzie" "sasha"
2003-07-31 "sven" "joe" "tina" "jack" "suzie" "sasha" "john" "luca"
提前感谢您的帮助。作为R的初学者,这给我带来了难题......
亲切的问候,
萨莫。
答案 0 :(得分:1)
假设m
是您的原始矩阵(即xts的coredata)。然后你可以得到你想要的东西:
> nams <- colnames(m)
> t( apply(m, 1, function(r) nams[ order(r) ] ) )
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
2003-05-29 "john" "joe" "tina" "jack" "suzie" "sasha" "sven" "luca"
2003-06-27 "luca" "john" "joe" "tina" "jack" "suzie" "sasha" "sven"
2003-07-30 "sven" "luca" "john" "joe" "tina" "jack" "suzie" "sasha"
2003-07-31 "sven" "joe" "tina" "jack" "suzie" "sasha" "john" "luca"
请注意,order(r)
会将向量r
转换为向量p
,以便顺序
r[p[1]], r[ p[2] ], r[ p[3] ], ...
处于非递减顺序,默认情况下是将NAs推送到最后。