扩展xts对象的索引

时间:2017-03-05 01:41:12

标签: r xts

我想用其他xts对象的索引创建一个xts对象,但是增强,即更长:在开始之前和结束之后。 例如。为了在相应的索引之后添加5个句点,我将使用:

data(sample_matrix)
xts_object <- as.xts(sample_matrix, descr='my new xts object')

add_right <- 5
seq(as.Date(end(xts_object)), by = unclass(periodicity(xts_object))$label, length = (add_right+1))[-1]

2个问题:

  1. 这总是有用吗(我会在功能中使用它)
  2. 如何在相应的开始之前添加句点?
  3. 提前致谢!

1 个答案:

答案 0 :(得分:2)

1。这总是有用吗(我会在功能中使用它)

2。如何在相应的开始之前添加句点?

以下是在开始和结束边界上扩展索引的示例,默认情况下使用NA值进行填充。如果数据列匹配,您还可以使用rbind(xts1, xts2)在开头或结尾轻松添加实际xts数据。

# add dateFormat = "Date" to avoid misaligned timestamps
# in relation to time component HH:MM:SS when `rbind`ing with
# Date type indexes (as opposed to POSIXct type indexes):
xts_object <- as.xts(sample_matrix, descr='my new xts object', dateFormat="Date") 

my_periodicity <- unclass(periodicity(xts_object))$label
add_right <- 5
v_dates_end <- seq(as.Date(end(xts_object)),
                   by = my_periodicity,
                   length.out = (add_right+1))[-1]

st_date <- as.Date(start(xts_object))
v_dates_start <- seq(from = st_date - 5,
                     to = st_date - 1,
                     by = my_periodicity)

x_expand_time_index <- xts(, order.by = c(v_dates_start, v_dates_end))
# Note the fill argument could be replaced by say 0, 1, NaN, etc
x <- merge(xts_object, x_expand_time_index, fill = NA)

head(x)
#                Open     High      Low    Close
# 2006-12-28       NA       NA       NA       NA
# 2006-12-29       NA       NA       NA       NA
# 2006-12-30       NA       NA       NA       NA
# 2006-12-31       NA       NA       NA       NA
# 2007-01-01       NA       NA       NA       NA
# 2007-01-02 50.03978 50.11778 49.95041 50.11778
tail(x)
#                Open     High      Low    Close
# 2007-06-30 47.67468 47.94127 47.67468 47.76719
# 2007-07-01       NA       NA       NA       NA
# 2007-07-02       NA       NA       NA       NA
# 2007-07-03       NA       NA       NA       NA
# 2007-07-04       NA       NA       NA       NA
# 2007-07-05       NA       NA       NA       NA