Rank ordering xts objects representing some property of equities using 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 开发者_Python百科 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.Suppose m
is your original matrix (i.e. the coredata of the xts). You can then get what you want with:
> 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"
Note that order(r)
converts a vector r
to a vector p
such that the sequence
r[p[1]], r[ p[2] ], r[ p[3] ], ...
is in non-decreasing order, and the default is to push NAs to the end.
精彩评论