简体   繁体   中英

R How to use “sort” function at “period.apply”?

I want to order my time series in descending order (from maximum value to minimum value) for each year.

  1. At the first time, I apply the function "sort" with "apply", here it works but all dates are mixed.

     library(xts) library(PerformanceAnalytics) data(edhec) head(edhec) edhec_4yr <- edhec["1997/2001"] ep <- endpoints(edhec_4yr, "year") # "sort" function with apply Ok s.ap=apply(edhec_4yr[,1],2,sort,decreasing = TRUE) s.ap 

To separate the descending order of the values for each year, I try to apply the "sort" function with "period.apply" but it only gives the first value (maximum value) for each year!

My goal is to have all the data but just in descending order for each year.

>  #"sort" with period.apply (Juste the first value for each year!
> Why!!!!)
>     
>     s.per.ap=period.apply(edhec_4yr[,1], INDEX = ep, function(x) apply(x,2,sort,decreasing = TRUE))
>     s.per.ap

Indeed, I want to have this:

    Convertible Arbitrage
1997-06 0.0212
1997-07 0.0193
1997-05 0.0156
1997-08 0.0134
1997-02 0.0123
1997-09 0.0122
1997-01 0.0119
1997-10 0.0100
1997-04 0.0086
1997-03 0.0078
1997-12 0.0068
1997-11 0.0000

1998-11 0.0269
1998-02 0.0146
1998-01 0.0145
1998-03 0.0144
1998-04 0.0126
1998-12 0.0113
1998-07 0.0060
1998-05 0.0056
1998-06 -0.0006
1998-09 -0.0196
1998-10 -0.0214
1998-08 -0.0319
......

Can you helpe me how to improve my function with "period.apply" !

Thanks

Using sort with period.apply() does not return just the first value. It returns an xts with a row for each year and a column for each month, with the columns sorted in descending order.

R> period.apply(edhec_4yr[,1], ep, function(x) apply(x,2,sort,decreasing = TRUE))
             [,1]   [,2]   [,3]   [,4]   [,5]   [,6]
1997-12-31 0.0212 0.0193 0.0156 0.0134 0.0123 0.0122
1998-12-31 0.0269 0.0146 0.0145 0.0144 0.0126 0.0113
1999-12-31 0.0243 0.0219 0.0166 0.0140 0.0136 0.0124
2000-12-31 0.0267 0.0243 0.0227 0.0223 0.0179 0.0162
2001-12-31 0.0344 0.0182 0.0162 0.0157 0.0142 0.0117
             [,7]   [,8]    [,9]   [,10]   [,11]   [,12]
1997-12-31 0.0119 0.0100  0.0086  0.0078  0.0068  0.0000
1998-12-31 0.0060 0.0056 -0.0006 -0.0196 -0.0214 -0.0319
1999-12-31 0.0102 0.0101  0.0096  0.0082  0.0048  0.0045
2000-12-31 0.0149 0.0141  0.0093  0.0052 -0.0002 -0.0081
2001-12-31 0.0091 0.0080  0.0078  0.0033  0.0012 -0.0094

The example output of what you want simply cannot be an xts/zoo object, because xts/zoo objects must have an ordered index.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM