我有一个具有以下属性的ts:
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"
我正在寻找一种简单的方法来创建一个时间间隔,其结果如下:
Y$Date[grep("2001",Y$Date)]
从2001年提取所有值,仅采用以下形式:
Y$Date["2001" =< Y$Date < "2002"] #or
Y$Date["2001" =< Y$Date & Y$Date < "2002"] #for that matter.
因为它允许我设置时间间隔,例如从2001年到2005年等。
打字:
Y$Date[Y$Date < "2002"]
导致R重新调整整个系列。我已经使用cut()将ts分成几个区间:
y<-cut(Y$Date,breaks="year") #and
as.data.frame(table(y))
两者都做得很好,但确实为我提供了我想要的灵活性。
非常感谢您的帮助,如果我能以任何方式帮助您解决此问题,请与我们联系。
非常感谢。
答案 0 :(得分:1)
将日期转换为xts
类对象,请查看?xts
中library(xts)
的示例:
date <- as.xts(Y$Date, descr='my new xts object')
现在,您可以按以下格式(取自?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