3

我确实有一个看起来像这样的时间序列(分钟值):

   "timestamp", value 
    "2012-04-09 05:03:00",2
    "2012-04-09 05:04:00",4
    "2012-04-09 05:05:00",5
    "2012-04-09 05:06:00",0
    "2012-04-09 05:07:00",0
    "2012-04-09 05:08:00",3
    "2012-04-09 05:09:00",0
    "2012-04-09 05:10:00",1

有没有一种简单的方法可以在一天中的一个小时内绘制这些值:X 轴从 1 到 24 小时(或 0 和 23)。所以 - 在第 5 小时等 5:00 和 5:59 之间的所有值。它不依赖于哪个日期,我只是对一天中的时间感兴趣。谢谢!

附加问题:我可以将其绘制为箱线图吗?现在它是plot(df$hh,df$coredata.._data..)动物园格式。

4

3 回答 3

4

读取创建动物园对象的数据z,然后创建hour变量并绘图:

library(zoo)

# read in data
Lines <- ' "timestamp", value 
    "2012-04-09 05:03:00",2
    "2012-04-09 05:04:00",4
    "2012-04-09 05:05:00",5
    "2012-04-09 05:06:00",0
    "2012-04-09 05:07:00",0
    "2012-04-09 05:08:00",3
    "2012-04-09 05:09:00",0
    "2012-04-09 05:10:00",1
'
z <- read.zoo(text = Lines, header = TRUE, sep = ",", tz = "")

# plot
hour <- as.POSIXlt(time(z))$hour
plot(hour, z)

截屏

于 2013-04-17T14:29:33.113 回答
3

使用xts包,您可以使用.indexhour通用函数将 xts 对象的索引格式化为小时。

例如,我读取数据,

dat <- read.zoo(text='timestamp, value 
    "2012-04-09 05:03:00",2
    "2012-04-09 05:04:00",4
    "2012-04-09 05:05:00",5
    "2012-04-09 05:06:00",0
    "2012-04-09 05:07:00",0
    "2012-04-09 05:08:00",3
    "2012-04-09 05:09:00",0
    "2012-04-09 05:10:00",1',header=TRUE,tz='',index=0:1,sep=',')

transform(dat, hh = .indexhour(dat))
                    coredata.._data.. hh
2012-04-09 05:03:00                 2  5
2012-04-09 05:04:00                 4  5
2012-04-09 05:05:00                 5  5
2012-04-09 05:06:00                 0  5
2012-04-09 05:07:00                 0  5
2012-04-09 05:08:00                 3  5
2012-04-09 05:09:00                 0  5
2012-04-09 05:10:00                 1  5
于 2013-04-17T13:21:08.313 回答
3

您可以通过将这些时间转换为POSIXlt类,然后"hours"从结果列表中为每个类提取组件,使用 sapply 返回一个向量来获得小时向量。然后,您可以将其添加到原始数据框中:

df <- read.table( text = "timestamp, value 
    2012-04-09 05:03:00,2
    2012-04-09 05:04:00,4
    2012-04-09 05:05:00,5
    2012-04-09 05:06:00,0
    2012-04-09 05:07:00,0
    2012-04-09 05:08:00,3
    2012-04-09 05:09:00,0
    2012-04-09 05:10:00,1" , h = T , sep = "," )

# Convert to POSIX class
df$timestamp <- as.POSIXlt(df$timestamp)

# Each entry in timestamp has some hidden attributes
attributes(df$timestamp[1])
$names
# [1] "sec"   "min"   "hour"  "mday"  "mon"   "year"  "wday"  "yday"  "isdst"

hours <- sapply( seq_len( nrow( df ) ) , function(x) df$timestamp[x]$hour )

df$hours <- hours

df
#               timestamp value hours
#   1 2012-04-09 05:03:00     2     5
#   2 2012-04-09 05:04:00     4     5
#   3 2012-04-09 05:05:00     5     5
#   4 2012-04-09 05:06:00     0     5
#   5 2012-04-09 05:07:00     0     5
#   6 2012-04-09 05:08:00     3     5
#   7 2012-04-09 05:09:00     0     5
#   8 2012-04-09 05:10:00     1     5
于 2013-04-17T12:38:36.097 回答