Search code examples
rchron

converting times using Chron not working as intended


I have the following vector containing time stamps. These time stamps are recorded as factors.

times<-as.factor(c("8:24", "9:17","11:52","1:49","9:36"))

I want to convert them in to time objects using the chron package. And I have used the following code

library(chron)

chron(as.character(times), format = "h:m")

however, when I run this it states

Error in widths[, fmt$periods, drop = FALSE] : subscript out of bounds

how do I get around this issue


Solution

  • You must supply secoonds:

    times(paste0(times, ":00"))
    ## [1] 08:24:00 09:17:00 11:52:00 01:49:00 09:36:00
    

    These work too:

    times(c(as.matrix(read.table(text = as.character(times), sep = ":")) %*% c(1, 1/60)/24))
    ## [1] 08:24:00 09:17:00 11:52:00 01:49:00 09:36:00
    
    times(as.numeric(sub(":.*", "", times)) / 24 + as.numeric(sub(".*:", "", times)) / (24 * 60))
    ## [1] 08:24:00 09:17:00 11:52:00 01:49:00 09:36:00