[R] Converting time format

Rui Barradas ru|pb@rr@d@@ @end|ng |rom @@po@pt
Mon Sep 19 19:27:41 CEST 2022


Hello,

I will run the examples below with the following data:


x <- c("12:00", "12:15", "12:30", "12:45", "13:00", "13:15", "13:30",
        "13:45", "14:00", "14:15", "14:30", "14:45", "15:00", "15:15",
        "15:30", "15:45", "16:00", "16:15", "16:30", "16:45", "17:00",
        "17:15", "17:30", "17:45", "18:00")
b <- data.frame(time = x, myvar = sin(2*pi*seq_along(x)/length(x)))


Are they are saying is true, the vector b$myvar is a character vector 
and that's what is being displayed.

In what follows I will first give examples of base graphics. The times 
are first coerced to a proper time class with package chron.



library(chron)

b$time <- as.times(b$time)

# see ?plot.default for the meaning of
# argument 'type'
plot(myvar ~ time, b)
plot(myvar ~ time, b, type = "l")
plot(myvar ~ time, b, type = "b")



With ggplot2, there is no need to load a date/time class package, R can 
do it with ?as.POSXct but the labels are datetime_breaks and 
datetime_labels.



library(ggplot2)

b |>
   dplyr::mutate(time = paste(Sys.Date(), time),
                 time = as.POSIXct(time)) |>
   ggplot(aes(time, myvar)) +
   geom_line() +
   geom_point() +
   scale_x_datetime(date_breaks = "1 hour", date_labels = "%H:%M") +
   theme_bw()



Hope this helps,

Rui Barradas


Às 01:56 de 19/09/2022, Parkhurst, David escreveu:
> I have a dataframe obtained using read.csv from an excel file.  Its first column is times, running from 18:00 to 19:30.  If I want to plot other columns against time, do I need to convert those somehow, and how would I do that?
> 
> If I run plot(b$time,b$myvar) I get a decent plot, but a friend suggests that R is just treating those numbers as text, and putting them in alphabetical order.  True?
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list