我只是有时间序列的一列中的数据文件:
'2012-02-01 17:42:44'
'2012-02-01 17:42:44'
'2012-02-01 17:42:44'
......我要拆分的数据建立这样,我都不得不小时的顶部计数。 说:
'2012-02-01 17:00:00' 20
'2012-02-01 18:00:00' 30
的“20”和“30”表示时间序列条目的该超时周期的数目。 我希望能够以图形化的时间是VS“计数”。 我怎样才能做到这一点有R?
这是我目前的线图的情节。
library(ggplot2)
req <- read.table("times1.dat")
summary(req)
da <- req$V2
db <- req$V1
time <- as.POSIXct(db)
png('time_data_errs.png', width=800, height=600)
gg <- qplot(time, da) + geom_line()
print(gg)
dev.off()
这听起来像你想用cut
许多值在一个小时内是如何发生弄清楚。
这是通常有益的,如果你能提供一些样本数据。 下面是一些:
set.seed(1) # So you can get the same numbers as I do
MyDates <- ISOdatetime(2012, 1, 1, 0, 0, 0, tz = "GMT") + sample(1:27000, 500)
head(MyDates)
# [1] "2012-01-01 01:59:29 GMT" "2012-01-01 02:47:27 GMT" "2012-01-01 04:17:46 GMT"
# [4] "2012-01-01 06:48:39 GMT" "2012-01-01 01:30:45 GMT" "2012-01-01 06:44:13 GMT"
您可以使用table
和cut
(与参数breaks="hour"
(见?cut.Date
获得更多信息))找到每小时的频率。
MyDatesTable <- table(cut(MyDates, breaks="hour"))
MyDatesTable
#
# 2012-01-01 00:00:00 2012-01-01 01:00:00 2012-01-01 02:00:00 2012-01-01 03:00:00
# 59 73 74 83
# 2012-01-01 04:00:00 2012-01-01 05:00:00 2012-01-01 06:00:00 2012-01-01 07:00:00
# 52 62 64 33
# Or a data.frame if you prefer
data.frame(MyDatesTable)
# Var1 Freq
# 1 2012-01-01 00:00:00 59
# 2 2012-01-01 01:00:00 73
# 3 2012-01-01 02:00:00 74
# 4 2012-01-01 03:00:00 83
# 5 2012-01-01 04:00:00 52
# 6 2012-01-01 05:00:00 62
# 7 2012-01-01 06:00:00 64
# 8 2012-01-01 07:00:00 33
最后,这里的的线图MyDatesTable
对象:
plot(MyDatesTable, type="l", xlab="Time", ylab="Freq")
cut
可以处理的范围内的时间间隔的。 例如,如果你想为制表每隔30分钟,你可以很容易地适应breaks
的说法来处理:
data.frame(table(cut(MyDates, breaks = "30 mins")))
# Var1 Freq
# 1 2012-01-01 00:00:00 22
# 2 2012-01-01 00:30:00 37
# 3 2012-01-01 01:00:00 38
# 4 2012-01-01 01:30:00 35
# 5 2012-01-01 02:00:00 32
# 6 2012-01-01 02:30:00 42
# 7 2012-01-01 03:00:00 39
# 8 2012-01-01 03:30:00 44
# 9 2012-01-01 04:00:00 25
# 10 2012-01-01 04:30:00 27
# 11 2012-01-01 05:00:00 33
# 12 2012-01-01 05:30:00 29
# 13 2012-01-01 06:00:00 29
# 14 2012-01-01 06:30:00 35
# 15 2012-01-01 07:00:00 33
更新
既然你试图用积ggplot2
,这里有一个方法(不知道这是否是最好的,因为我通常使用基础R的图形,当我需要)。
创建一个data.frame
表中的(如上所示),并添加一个虚设“基团”变量并画出其如下:
MyDatesDF <- data.frame(MyDatesTable, grp = 1)
ggplot(MyDatesDF, aes(Var1, Freq)) + geom_line(aes(group = grp))
文章来源: Split time series data into time intervals (say an hour) and then plot the count