Lorenzo Rigamonti
Lorenzo Rigamonti

Reputation: 1775

Problems with defining the stucture of a list in R

I have a function which create a list of different statistics computed as follows:

RiskStats = list(stdev,sharpe,downdev,sortino,maxDD,calmar,currDD)

> RiskStats
[[1]]
             Index
StdDev       3.2506

[[2]]
                                 Index
Annualized Sharpe Ratio (Rf=0%)      -1.2434

[[3]]
                                    Index
Downside Deviation (MAR = 0%)        3.194

[[4]]
                              Index
Sortino Ratio (MAR = 0%)      -1.2655

[[5]]
            Index
maxDD      -8.9467

[[6]]
                  Index
Calmar Ratio     -0.44846

[[7]]
                 Index
Current DD       -8.543

I want to set a structure for this list (7 rows and 1 column) and we can simply write

dim(RiskStats) <- c(7,1)

Why in the results we get for certain results [List,1] instead of the correct statistic computed?

  > RiskStats
                    Index
Annual volatility  3.2506      
Sharpe ratio       -1.2434     
Downside deviation 3.194       
Sortino ratio      -1.2655     
Maximum Drawdown   List,1      
Calmar ratio       -0.44846    
Current drawdown   List,1   

Upvotes: 0

Views: 71

Answers (2)

Jilber Urbina
Jilber Urbina

Reputation: 61214

Using this data

dput(RiskStats)
RiskStats <- list(structure(list(Index = 3.2506), .Names = "Index", row.names = "StdDev", class = "data.frame"), 
    structure(list(Index = -1.2434), .Names = "Index", row.names = "Annualized_Sharpe_Ratio_Rf", class = "data.frame"), 
    structure(list(Index = 3.194), .Names = "Index", row.names = "Downside_Deviation_MAR_0", class = "data.frame"), 
    structure(list(Index = -8.9467), .Names = "Index", row.names = "maxDD", class = "data.frame"), 
    structure(list(Index = -0.44846), .Names = "Index", row.names = "Calmar_Ratio", class = "data.frame"), 
    structure(list(Index = -8.543), .Names = "Index", row.names = "Current_DD", class = "data.frame"))

You can achieve your goal by several ways, here are some of them:

# Alternative 1  (suggested by @Roman Luštrik)
do.call(rbind, RiskStats)  # I think this is the best one 

# Alternative 2
Reduce(rbind, RiskStats)

# Alternative 3
t(data.frame(lapply(RiskStats, t))) # It's not so good, but it works.

Whatever alternative you chose you will end up with the following result:

                              Index
StdDev                      3.25060
Annualized_Sharpe_Ratio_Rf -1.24340
Downside_Deviation_MAR_0    3.19400
maxDD                      -8.94670
Calmar_Ratio               -0.44846
Current_DD                 -8.54300

Upvotes: 1

scottyaz
scottyaz

Reputation: 722

The reason is because drawdown and maximum drawdown are lists themselves where as the others are likely some other data structure.

try unlist() on those elements.

Upvotes: 0

Related Questions