问题
I do have a time-series looking like this (minute values):
"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
Is there an easy way to plot these values over the hour of the day: X-Axis from 1 to 24 hours (or 0 and 23). So - all values between 5:00 and 5:59 over the 5th hour etc. It doesn't depend wich date, I am just interested in the houers of the day. Thank you!
Additional Question: Can I plot this as a boxplot? Right now it's plot(df$hh,df$coredata.._data..)
in zoo format.
回答1:
Using xts
package, you can use .indexhour
Generic functions to format the index of an xts object to hours.
For example , I read the data,
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
回答2:
Read the data creating zoo object z
and then create hour
variable and plot:
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)

回答3:
You could get a vector of the hours by converting those times to POSIXlt
classes and then extracting the "hours"
component from the resulting list for each one, using sapply to return a vector. You can then add this to the original dataframe:
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
来源:https://stackoverflow.com/questions/16059965/plot-value-over-hour-of-day-with-xts-zoo-r