2016-11-27 81 views
0

我正在努力將一些數據轉換爲一個季度時間xts系列對象。首先我的數據不是一個合適的基於時間的對象現在as.yearqtr表現得我無法理解。創建季度`xts`時間序列對象使用plot.xts

我想要對象df進行轉換,以便我可以用我的最終目標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 
+1

列'yrQ'顯然並不表示季度,因爲沒有7個季度在2016年是您的原始數據每月?您希望如何將其彙總爲季度(總和,平均值,OHLC ...)? –

+0

@ChrisHaug,我真的很抱歉。在我應該上牀睡覺之後,我正在這樣做(@ R.S也有禮貌地識別這種心理失誤),我會盡快更新我的問題。謝謝! –

回答

1

你在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) 
+0

謝謝你的回答!我想我昨天晚上熬了太晚。正如你和@ChrisHaug指出'yrQ'顯然不表示季度,而是幾個月。儘管我精神失常,但你的回答是非常清楚,寫得很好。謝謝! –

+0

它感到高興。順便說一句,我個人喜歡那個quantmod OHLC樣式圖表。 –