首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >创建用于plot.xts的季度“with”时间序列对象

创建用于plot.xts的季度“with”时间序列对象
EN

Stack Overflow用户
提问于 2016-11-27 16:49:03
回答 1查看 776关注 0票数 0

我正在努力将一些数据转换为一个季度时间xts系列对象。首先,我的数据不是一个合适的基于时间的对象,现在as.yearqtr正在运行,我无法理解。

我希望对对象df进行转换,这样我就可以用plot.xts来绘制它,这是我的最终目标,但是我被困在下面。

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-11-27 18:45:47

您在df中拥有的数据似乎是月数据,因为它运行的时间已经超过了4。

在这种情况下,我想应该使用as.yearmon,然后从那里到to.quarterly。不过,如果没有OHLC图表,它就不会画得那么好,所以我也查了另一个选项。看看你怎么想吧。

以下是我的尝试:

代码语言:javascript
复制
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)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40831347

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档