PerformanceAnalytics Numbers to Percent %

喜欢而已 提交于 2019-12-02 06:06:41

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!