Simple time interval in R

2019-09-20 06:49发布

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)]

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.

As it would allow me to set time intervals such as from 2001 - 2005 etc.

Typing:

Y$Date[Y$Date < "2002"] 

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.

Thank you very much.

标签: r time intervals
1条回答
Luminary・发光体
2楼-- · 2019-09-20 07:18

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')

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
查看更多
登录 后发表回答