问题描述
我的ts具有以下属性:
I've got a ts with the following properties:
summary(Y$Date)
Min. 1st Qu. Median Mean 3rd Qu. Max.
"2001-01-01 05:30:00" "2004-03-15 10:40:30" "2007-01-03 04:00:00" "2006-11-11 15:53:11" "2009-08-13 12:00:00" "2011-12-30 12:30:00"
str(Y$Date)
POSIXlt[1:174110], format: "2001-01-01 12:00:00" "2001-01-01 05:30:00" "2001-01-02 01:30:00" "2001-01-02 02:00:00" "2001-01-02 02:00:00" "2001-01-02 02:01:00" "2001-01-02 04:00:00" "2001-01-02 04:00:00" ...
length(Y$Date)
[1] 174110
Y$Date[1:5]
[1] "2001-01-01 12:00:00" "2001-01-01 05:30:00" "2001-01-02 01:30:00" "2001-01-02 02:00:00" "2001-01-02 02:00:00"
我正在寻找一种创建时间间隔的简单方法,该时间间隔显示与以下结果相同的结果:
I am looking for a simple way to create a time interval which presents the same result as:
Y$Date[grep("2001",Y$Date)]
仅以以下形式提取2001年的所有值:
which extracts all values from 2001, only in the form of:
Y$Date["2001" =< Y$Date < "2002"] #or
Y$Date["2001" =< Y$Date & Y$Date < "2002"] #for that matter.
因为它可以让我设置时间间隔,例如从2001年到2005年等.
As it would allow me to set time intervals such as from 2001 - 2005 etc.
键入:
Y$Date[Y$Date < "2002"]
R调整整个序列的结果.我已经使用cut()将ts分为几个间隔:
results in R retuning the entire series.I have already split the ts into several intervals using cut():
y<-cut(Y$Date,breaks="year") #and
as.data.frame(table(y))
两者都做得很好,但确实为我提供了所需的灵活性.
both do a pretty good job, but do provide me with the level of flexibility that I want.
非常感谢您的帮助,如果可以以任何方式帮助您解决此问题,请告诉我.
Your help is very much appreciated, please let me know if I can assist you in any way to resolve this issue.
非常感谢您.
推荐答案
将日期转换为xts
类对象请看library(xts)
中?xts
的示例:
convert the date to xts
class objects look at the example of ?xts
in library(xts)
:
date <- as.xts(Y$Date, descr='my new xts object')
现在,您可以提取以下格式的时间间隔(取自?xts
):
Now you can extract time intervals in the following format (taken from ?xts
):
date['2007'] # all of 2007
date['2007-03/'] # March 2007 to the end of the data set
date['2007-03/2007'] # March 2007 to the end of 2007
date['/'] # the whole data set
date['/2007'] # the beginning of the data through 2007
date['2007-01-03'] # just the 3rd of January 2007
这篇关于R中的简单时间间隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!