将多个列添加到一个xts对象中。

3

我对如何简洁地做到这一点感到有些困惑。我的解决方案使用 matrix(...) 工作,但似乎有点过于生硬。是否有更好的方法?

我有一个现有的 1 行 xts 对象(D1),以及来自外部来源的非 xts 向量(E1),我想将它们合并在一起:

library(quantmod)

getSymbols("SPY")
data = get("SPY")
is.xts(data)

# Extract a single row xts object
D1 = data[1,]
index(D1)
# Get the numerical part as a vector
D1v = as.vector(D1)

# New data from external source to be merged
E1 = c(5,6,7,8,9,10)

# Combine into new vector
G1 = c(D1v, E1)
G1

# This fails, I think because xts treats G1 
# like a 1-column object, not a 1-row object?
testXts1 = xts(G1, order.by = index(D1))

testXts2 = xts(matrix(G1, nrow=1), order.by = index(D1))
index(testXts2)
testXts2

我的问题是 matrix(G1, nrow=1) 是否是这种操作的预期方法,问题在于xts要求X和index(X)具有相同的维度。

谢谢!


1
你可以少打一些字:xts(t(G1), index(D1)) - GSee
1个回答

2

由于你想做的事情比较不寻常(只有一行xts是不寻常的),我认为你找到的习语可能是最好的选择。

我能想到的另一种方法是逐个添加每一列:

D1$a = 5
D1$b = 6
D1$c = 7
D1$d = 8
D1$e = 9

这将会得到:
> D1
           SPY.Open SPY.High SPY.Low SPY.Close SPY.Volume SPY.Adjusted a b c d e
2007-01-03   142.25   142.86  140.57    141.37   94807600       122.03 5 6 7 8 9

感谢您的回复。在其他类似问题中,使用名称是我找到的一种解决方案,但它似乎更适合添加1或2个新列。在我的情况下,我可能会收到50或100个,这需要太多的打字(对我来说!)。我怀疑我在这里做的事情是不常见的。我会在奇怪的时间收到一些数据,但希望将其保留在某种较大的xts上下文中。谢谢! - LGTrader
我尝试了一些循环的想法,但它们比你的矩阵方法更冗长。 - Darren Cook

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接