rtimechron

R Convert char to time


I have a column of military time values, df1$appt_times in the format of "13:30" All of them, 5 characters, "00:00". I have tried POSIXct but it added today's date to the values. I have also tried lubridate and couldn't get that to work. Most recently I am trying to use chron and am so far unsuccessful at that too

The goal is that once this is done I am going to group the times into factor levels, I cannot perform any conditional operations on them currently, unless I am wrong about that as well ;)

> df1$Time <-  chron(times = df1$appt_time)
Error in convert.times(times., fmt) : format h:m:s may be incorrect
In addition: Warning message:
In unpaste(times, sep = fmt$sep, fnames = fmt$periods, nfields = 3) :
  106057 entries set to NA due to wrong number of fields

also df1$Time <- chron(times(df1$appt_time)) same error as above

as well as different tries at being explicit with the format:

> df1$appt_time <- chron(df1$appt_time, format = "h:m")
Error in widths[, fmt$periods, drop = FALSE] : subscript out of bounds

I would be very grateful if someone could point out my error or suggest a better way to accomplish this task.


Solution

  • Not being able to find a solution to work with the time in the way I thought I came up with this DIIIIIRRRRRRRRRRRTY solution.

    #converted appt_time to POSIXct format, which added toady's date 
    df9$appt_time <- as.POSIXct(df9$appt_time, format = '%H:%M')
    
    #Since I am only interesting in creating a value based on if the time falls within a specific range I decided I could output this new value, 'unclassed', to a column and then manually eyeball the values I needed that corresponded to my ranges
    df9$convert <- unclass(df9$appt_time)
    
    #Using the, manually obtained, unclassed values I was able create the factor levels I wanted
    group_appt_time <- function(convert){
      ifelse (convert >= 1612624500 & convert <= 1612637100, 'Morning',
                      ifelse (convert >= 1612638000 & convert <= 1612647900, 'Mid-Day',
                              ifelse (convert >= 1612648800 & convert <= 1612658700, 'Afternoon',
                                      'Invalid Time')))
    }
    
    df9$appt_time_grouped <- as.factor(group_appt_time(df9$convert))
    

    This is a research project, not something I need to recreate in an ongoing manner so it works