【问题标题】:How to use list of xts objects like a 3d array in R?如何使用 xts 对象列表,如 R 中的 3d 数组?
【发布时间】:2020-03-16 19:14:51
【问题描述】:

我想以可以用作 3d 数组的方式访问 xts 对象列表。

这是示例数据。由于这只是一个示例,因此我在所有对象中保留了相同的数据。

data(sample_matrix)
sample.xts_1 <- as.xts(sample_matrix, descr='Object 1')
sample.xts_2 <- as.xts(sample_matrix, descr='Object 2')
sample.xts_3 <- as.xts(sample_matrix, descr='Object 3')

data_list = list(a = sample.xts_1, b = sample.xts_2, c = sample.xts_3)

这个数据看起来像这样 -

$a
           Open High  Low Close
2007-01-02 50.0 50.1 50.0  50.1
2007-01-03 50.2 50.4 50.2  50.4
$b
           Open High  Low Close
2007-01-02 50.0 50.1 50.0  50.1
2007-01-03 50.2 50.4 50.2  50.4
$c
           Open High  Low Close
2007-01-02 50.0 50.1 50.0  50.1
2007-01-03 50.2 50.4 50.2  50.4

有没有一种简单的方法可以按以下方式访问这些列表元素?

$open
            a    b    c 
2007-01-02 50.0 50.0 50.0 
2007-01-03 50.2 50.2 50.2 
2007-01-04 50.4 50.4 50.4 
2007-01-05 50.4 50.4 50.4 
2007-01-06 50.2 50.2 50.2 
2007-01-07 50.1 50.1 50.1 
2007-01-08 50.0 50.0 50.0 

$high
            a    b    c 
2007-01-02 50.1 50.1 50.1 
2007-01-03 50.4 50.4 50.4 
2007-01-04 50.4 50.4 50.4 
2007-01-05 50.4 50.4 50.4 
2007-01-06 50.2 50.2 50.2 
2007-01-07 50.2 50.2 50.2 
2007-01-08 50.1 50.1 50.1 

$low
            a    b    c 
2007-01-02 50.0 50.0 50.0 
2007-01-03 50.2 50.2 50.2 
2007-01-04 50.3 50.3 50.3 
2007-01-05 50.2 50.2 50.2 
2007-01-06 50.1 50.1 50.1 
2007-01-07 50.0 50.0 50.0 
2007-01-08 50.0 50.0 50.0 


$close
            a    b    c 
2007-01-02 50.1 50.1 50.1 
2007-01-03 50.4 50.4 50.4 
2007-01-04 50.3 50.3 50.3 
2007-01-05 50.3 50.3 50.3 
2007-01-06 50.2 50.2 50.2 
2007-01-07 50.0 50.0 50.0 
2007-01-08 50.0 50.0 50.0 

【问题讨论】:

    标签: r arrays list 3d xts


    【解决方案1】:

    一个选项是split 按列,transpose 输出和cbind 它一起

    library(purrr)
    out <- map(data_list, ~ asplit(.x, 2)) %>%
          transpose %>%
          map(~do.call(cbind, .x))
    
    map(out, head, 3)
    #$Open
    #                  a        b        c
    #2007-01-02 50.03978 50.03978 50.03978
    #2007-01-03 50.23050 50.23050 50.23050
    #2007-01-04 50.42096 50.42096 50.42096
    
    #$High
    #                  a        b        c
    #2007-01-02 50.11778 50.11778 50.11778
    #2007-01-03 50.42188 50.42188 50.42188
    #2007-01-04 50.42096 50.42096 50.42096
    
    #$Low
    #                  a        b        c
    #2007-01-02 49.95041 49.95041 49.95041
    #2007-01-03 50.23050 50.23050 50.23050
    #2007-01-04 50.26414 50.26414 50.26414
    
    #$Close
    #                  a        b        c
    #2007-01-02 50.11778 50.11778 50.11778
    #2007-01-03 50.39767 50.39767 50.39767
    #2007-01-04 50.33236 50.33236 50.33236
    

    【讨论】:

    • 谢谢阿克伦。结果符合预期。
    猜你喜欢
    • 1970-01-01
    • 2020-04-24
    • 2020-06-08
    • 2014-01-11
    • 2021-06-06
    • 2015-11-29
    • 2015-02-14
    • 2019-06-26
    • 1970-01-01
    相关资源
    最近更新 更多