使用xts作为查找表

时间:2015-12-15 13:40:54

标签: r xts lookup-tables

示例数据:

library(xts)
a <- seq(as.POSIXct("2010-01-01 00:00:00"), by = 600, length.out = 3)
b <- c(a, a)
lu <- xts(seq_along(a), a)
lu[b]

                    [,1]
2010-01-01 00:00:00    1
2010-01-01 00:10:00    2
2010-01-01 00:20:00    3

一个人如何查找&#34;对于lu中的时间戳,b的值为{1}}与b长度相同的xts对象,在本例中为:

                    [,1]
2010-01-01 00:00:00    1
2010-01-01 00:10:00    2
2010-01-01 00:20:00    3
2010-01-01 00:00:00    1
2010-01-01 00:10:00    2
2010-01-01 00:20:00    3

2 个答案:

答案 0 :(得分:3)

1)按名称索引 xts实际上不是正确的包,因为您想要的结果不能是有效的xts对象。而是尝试以下不使用任何包。输出向量的名称是时间的字符表示,向量值本身是所需的值:

lutable <- setNames(seq_along(a), a)
lutable[format(b)]

,并提供:

2010-01-01 00:00:00 2010-01-01 00:10:00 2010-01-01 00:20:00 2010-01-01 00:00:00 2010-01-01 00:10:00 2010-01-01 00:20:00 
                  1                   2                   3                   1                   2                   3 

2)匹配另一种可能性就是像这样使用match。结果是与b中的时间对应的值:

v <- seq_along(a) # test values
v[match(b, a)]
## [1] 1 2 3 1 2 3

答案 1 :(得分:1)

您期望的结果存在一个小问题; XTS默认订购时间戳。因此XTS对象的结果将是1,1,2,2,3,3。

以下内容可以为您提供一些见解:

lu[match(b, index(lu))] #XTS object returned - Timestamps are ordered by default 
data.frame(ts = index(lu), lu) [match(b, index(lu)),] #Using dataframes instead reproduce the expected result.