Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

keep only hour: minute:second from a "POSIXlt" "POSIXt" object

Tags:

r

I am making a plot in R (plotting three days of a time series in a single plot). I have a "POSIXlt" "POSIXt" vector and I need to keep only the time (hour,minutes...) without year, month,day.

"2004-09-08 13:50:00 GMT" ---> 13:50:00
"2004-09-08 14:00:00 GMT" ---> 14:00:00
"2004-09-08 14:10:00 GMT" ---> 14:10:00
"2004-09-08 14:20:00 GMT" ---> 14:20:00
"2004-09-08 14:30:00 GMT" ---> 14:30:00

Is that possible?

I have been able to make that all the elements in the vector have the same year/month/day. It works for my plot but I do not think is the appropiate solution.

"2004-09-08 13:50:00 GMT" ---> "2014-10-19 13:50:00 GMT"
"2004-09-08 14:00:00 GMT" ---> "2014-10-19 14:00:00 GMT"
"2004-09-08 14:10:00 GMT" ---> "2014-10-19 14:10:00 GMT"
"2004-09-08 14:20:00 GMT" ---> "2014-10-19 14:20:00 GMT"
"2004-09-08 14:30:00 GMT" ---> "2014-10-19 14:30:00 GMT"

Thank you

like image 990
Marina Avatar asked Oct 19 '14 17:10

Marina


1 Answers

Suppose we have POSIXct values x.

library(chron)

# input
y <- 1:5
x <- as.POSIXct(c("2004-09-08 13:50:00", "2004-09-08 14:00:00", "2004-09-08 14:10:00",
"2004-09-08 14:20:00", "2004-09-08 14:30:00"))

1) Convert them to chron class "times" and plot:

ti <- times(format(x, "%H:%M:%S"))
plot(y ~ ti)

2) or you could do this with zoo:

library(zoo)

z <- zoo(y, x)

# convert index to "times" class and plot
zz <- z
time(zz) <- times(format(time(zz), "%H:%M:%S"))
plot(zz)

2a) or use ggplot2 with autoplot.zoo to plot:

library(ggplot2)
autoplot(zz) + scale_x_chron(format = "%H:%M")

2b) We could also handle this solely through labelling rather than converting the index class. This uses zoo/ggplot2/scales but not chron times and simply relabels the X axis:

library(scales)
autoplot(z) + scale_x_datetime(breaks = "10 min", labels = date_format("%H:%M"))
like image 56
G. Grothendieck Avatar answered Nov 02 '22 08:11

G. Grothendieck