I want to access list of xts objects in such a way that it could be used as a 3d array.
Here is the sample data. Since this is just an example, I kept the same data in all objects.
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)
And this data looks like this -
$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
Is there a simple way to access these list elements in the following fashion?
$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
One option is to split
by column, transpose
the output and cbind
it together
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