将两个 xts 对象(矩阵)合并到 R 中的单个数组中
我有两个 xts 对象。
> require(quantmod)
> getSymbols("GLD;SLV")
[1] "GLD" "SLV"
> head(SLV, n=2)
SLV.Open SLV.High SLV.Low SLV.Close SLV.Volume SLV.Adjusted
2007-01-03 129.96 131.16 124.70 125.58 7480000 12.56
2007-01-04 126.04 127.97 125.45 125.80 3220000 12.58
> head(GLD, n=2)
GLD.Open GLD.High GLD.Low GLD.Close GLD.Volume GLD.Adjusted
2007-01-03 63.58 64.02 62.00 62.28 8061900 62.28
2007-01-04 62.07 62.50 61.52 61.65 4858600 61.65
> NROW(SLV) == NROW(GLD)
[1] TRUE
如何将这些单独的二维矩阵“堆叠”到单个三维数组中?
大致如下:
metal <- xts_stacking_function (GLD, SLV)
class(metal)
[1] "array"
metal[1,,1]
GLD.Open GLD.High GLD.Low GLD.Close GLD.Volume GLD.Adjusted
2007-01-03 63.58 64.02 62 62.28 8061900 62.28
I have two xts objects.
> require(quantmod)
> getSymbols("GLD;SLV")
[1] "GLD" "SLV"
> head(SLV, n=2)
SLV.Open SLV.High SLV.Low SLV.Close SLV.Volume SLV.Adjusted
2007-01-03 129.96 131.16 124.70 125.58 7480000 12.56
2007-01-04 126.04 127.97 125.45 125.80 3220000 12.58
> head(GLD, n=2)
GLD.Open GLD.High GLD.Low GLD.Close GLD.Volume GLD.Adjusted
2007-01-03 63.58 64.02 62.00 62.28 8061900 62.28
2007-01-04 62.07 62.50 61.52 61.65 4858600 61.65
> NROW(SLV) == NROW(GLD)
[1] TRUE
How can you 'stack' these separate two-dimensional matrices into a single three-dimensional array?
Something along the lines of the following:
metal <- xts_stacking_function (GLD, SLV)
class(metal)
[1] "array"
metal[1,,1]
GLD.Open GLD.High GLD.Low GLD.Close GLD.Volume GLD.Adjusted
2007-01-03 63.58 64.02 62 62.28 8061900 62.28
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不认为 xts 对象支持 3d 数组。您可能需要一个像下面这样的丑陋的解决方案。将所有内容放入数组中会将内容强制为数值。但至少这保留了日期索引,尽管格式不同,因为数组只能有一种数据类型。
I don't think xts objects support 3d arrays. You'll probably need an ugly solution like the one below. Putting everything into an array coerces things to numeric values. But at least this preserves the date index, albeit in a different format because arrays can only have one data type.
鉴于您的最新评论,我认为您可以通过以下两种方式之一执行您想要的操作:
lapply
与 xts 对象列表一起使用eapply
与存储在自己的 xts 对象中使用 #2 使用 getSymbols 的示例(请注意,
eapply
返回一个列表):Given your latest comment, I think you could do what you want in one of two ways:
lapply
with a list of xts objectseapply
with xts objects stored in their own environmentAn example of #2 using getSymbols (note that
eapply
returns a list):