使用 R 对表示股票某些属性的 xts 对象进行排名排序
我正在尝试对股票进行排名(例如按回报)。因此,我希望收到一个包含按升序/降序排列的股票名称(此排序函数的参数)的表格,并正确处理 NA(移动到每行的末尾)。我真的想不出一种优雅的方法来做到这一点。
下面是我想要的示例:
这是 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 列,...请注意,对于最后一行,我需要将 NA 移至末尾(最后两列)或跳过的案例...
[,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 的初学者,这对我来说是一个难题......
亲切的问候,
萨摩。
I am trying to rank order equities (by return for example). As a result I would like to receive a table containing names of stocks in ascending/descending order (parameter to this rank order function) with proper handling of NAs (moved at the end of each row). I really can't figure out an elegant way to do this.
Below is an example of what I want:
This is coredata of xts object representing some property at different times:
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
I need a dataframe which in each row (for each date) displays the column name from previous dataframe of best ranked (based on a property) in column 1, second best in column 2,... Please note that for the last row I need cases with NAs moved to the end (last two columns) or skipped...
[,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"
Thanks in advance for your help. Being a beginner in R this poses to hard of a problem for me...
Kind regards,
Samo.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设 m 是您的原始矩阵(即 xts 的 coredata)。然后,您可以得到您想要的:
请注意,
order(r)
将向量r
转换为向量p
,使得序列r[p[1]], r[ p[2] ], r[ p[3] ], ...
按非递减顺序排列,默认将 NA 压入结尾。Suppose
m
is your original matrix (i.e. the coredata of the xts). You can then get what you want with:Note that
order(r)
converts a vectorr
to a vectorp
such that the sequencer[p[1]], r[ p[2] ], r[ p[3] ], ...
is in non-decreasing order, and the default is to push NAs to the end.