在R中定义列表结构的问题

时间:2013-02-06 11:02:01

标签: r list

我有一个函数可以创建一个计算如下不同统计信息的列表:

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

我想为这个列表设置一个结构(7行和1列),我们可以简单地写

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

为什么我们得到某些结果的结果[List,1]而不是计算出正确的统计量?

  > 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   

2 个答案:

答案 0 :(得分:1)

使用此数据

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"))

您可以通过多种方式实现目标,其中包括以下几种方法:

# 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.

无论您选择哪种方案,最终都会得到以下结果:

                              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

答案 1 :(得分:0)

原因是因为下拉和最大下降是列表本身,而其他可能是其他数据结构。

尝试对这些元素进行unlist()。