簡體   English   中英

創建季度`xts`時間序列對象以與plot.xts一起使用

[英]creating quarterly `xts` time-series object for use with plot.xts

我正在將一些數據轉換為每季度xts系列對象。 首先,我的數據不是適當的基於時間的對象 ,現在, as.yearqtr表現as.yearqtr ,我無法理解。

我希望對對象df進行轉換,以便可以使用我的最終目標plot.xts對其進行plot.xts ,但是我被卡住,如下所示。

df <- structure(list(yrQ = structure(1:7, .Label = c("2016-1", "2016-2", 
"2016-3", "2016-4", "2016-5", "2016-6", "2016-7"), class = "factor"), 
    a = c(4.14, 2.83, 3.71, 4.15, 4.63, 4.91, 5.31), b = c(4.25, 
    3.5, 3.5, 3.5, 3.5, 3.5, 5)), .Names = c("yrQ", "a", "b"
), row.names = c(NA, 7L), class = "data.frame")
df
#      yrQ    a    b
# 1 2016-1 4.14 4.25
# 2 2016-2 2.83 3.21
# 3 2016-3 3.71 3.21
# 4 2016-4 4.15 3.21
# 5 2016-5 4.63 3.21
# 6 2016-6 4.91 3.21
# 7 2016-7 5.31 5.00

# install.packages(c("xts"), dependencies = TRUE)
library(xts)
xts(df, order.by = df[,1])
# Error in xts(df, order.by = df[, 1]) : 
#   order.by requires an appropriate time-based object

df$yrQ <- as.yearqtr(df$yrQ)
df    
#       yrQ    a    b
# 1 2016 Q1 4.14 4.25
# 2 2016 Q2 2.83 3.21
# 3 2016 Q3 3.71 3.21
# 4 2016 Q4 4.15 3.21
# 5  NA QNA 4.63 3.21
# 6  NA QNA 4.91 3.21
# 7  NA QNA 5.31 5.00

df中的數據似乎是每月數據,因為它的運行時間超過了4。

在那種情況下,我想該走的路是使用as.yearmon並從那里到to.quarterly 如果沒有OHLC圖表,它的繪制效果並不理想,因此我也查找了另一個選擇。 看看您的想法。

這是我的嘗試:

require(xts)
df <- structure(list(yrQ = structure(1:7, .Label = c("2016-1", "2016-2", 
"2016-3", "2016-4", "2016-5", "2016-6", "2016-7"), class = "factor"), 
    a = c(4.14, 2.83, 3.71, 4.15, 4.63, 4.91, 5.31), b = c(4.25, 
    3.5, 3.5, 3.5, 3.5, 3.5, 5)), .Names = c("yrQ", "a", "b"
), row.names = c(NA, 7L), class = "data.frame")
df


# using yearmon to create xts
myxts<- xts(df[,-1], order.by = as.yearmon(as.character(df[,1])  ))

myxts

#using to.quarterly .. cannot be used simultaneously with both columns
#guess that would need apply and Reduce

myxtsQ<- to.quarterly(myxts$a)
myxtsQ
plot(myxtsQ) 
# require(quantmod)
# quantmod::chartSeries(myxtsQ)



# One option seems to be indexing 
# though it seems XTS does not support recycling of boolean indices
#so we need to create a list of indices

indx<- rep( c(T,F,F), ceiling(nrow(myxts)/3 ))
indx
myxtsQ<- myxts[indx,]
plot.xts(myxtsQ)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM