[R] Converting time format

Parkhurst, David p@rkhur@ @end|ng |rom |nd|@n@@edu
Mon Sep 19 20:24:55 CEST 2022

Thank you.

From: Rui Barradas <ruipbarradas using sapo.pt>
Date: Monday, September 19, 2022 at 1:28 PM
To: Parkhurst, David <parkhurs using indiana.edu>, R-help using r-project.org <R-help using r-project.org>
Subject: Re: [R] Converting time format

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.


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


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") +

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.

	[[alternative HTML version deleted]]

More information about the R-help mailing list