2017-03-05 40 views
1

我想創建一個xts對象與其他xts對象的索引,但增強,即更長:在開始之前和結束之前。 例如對於相應的索引後,加入5段,我將使用:擴展xts對象的索引

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. 如何添加在相應的開始之前的時期?

在此先感謝!

回答

1

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 
+0

非常感謝約書亞! – 4554888