PerformanceAnalytics Numbers to Percent %
Asked Answered
B

2

1

I want to know if it is possible to make the table output in this R package a % instead of a numeric.

table.AnnualizedReturns(indOver, Rf=0)

                          SP500  
Annualized Return         0.0732
Annualized Std Dev        0.1951
Annualized Sharpe (Rf=0%) 0.3752

So the 1st one 0.0732 I would like to see as 0.07%

Bullfinch answered 19/11, 2014 at 9:32 Comment(1)
Any chance of a reproducible example? If the table is that simple it might be easy enough to get the values themselves and format the table yourself.Hexagon
H
3

The return value from that function is a data frame, so the question is how to make a column of a data frame print with a percentage sign.

Reproducible example follows.

> require(PerformanceAnalytics)
> data(managers)
> tb =      table.AnnualizedReturns(managers[,1],Rf=0)
> tb
                            HAM1
Annualized Return         0.1375
Annualized Std Dev        0.0888
Annualized Sharpe (Rf=0%) 1.5491

Now we define a new class and a format function that displays with a percent sign:

> format.pc = function(x,...){sprintf('%0.2f%%',x)}
> class(tb[,1])="pc"

And now, as if by magic:

> tb
                           HAM1
Annualized Return         0.14%
Annualized Std Dev        0.09%
Annualized Sharpe (Rf=0%) 1.55%

The underlying values have not been changed:

> tb[,1]
[1] 0.1375 0.0888 1.5491
attr(,"class")
[1] "pc"

they are just in a vector of this new class.

Hexagon answered 19/11, 2014 at 10:4 Comment(3)
One further question, I have 3 columns in my data frame by tweaking your code like this I still dont achieve the goal on all 3 columns only the 1st one: class(tb[,1:3])="pc"Bullfinch
Loop it for(i in 1:ncol(tb)){class(tb[,i])="pc"}Hexagon
You should probably tick the little tick to mark this question as answered... ta.Hexagon
P
2

One way formatting the string correctly is:

sprintf('%0.2f%%', 0.0567)    # Note I use %% to get a percent sign in the output
[1] "0.06%"

Getting this to work in table.AnnualizedReturns will mean editing the code. You could make a copy, and edit the code according to your wishes. Alternatively, you could contact the writer of the package that contains this function and propose the change.

Parsaye answered 19/11, 2014 at 9:41 Comment(1)
thanks when I do this 'sprintf('%0.2f%%',indOver[1,3])' I am able to get 1 of the numbers to turn into a % but it seems to only allow 1 number not the other numbers in the data frame.Bullfinch

© 2022 - 2024 — McMap. All rights reserved.