-4

Say I have a column in my data frame containing only objects of strings:

"00:20:10"
"02:12:10"

etc

I want to just convert these strings to the corresponding time type object (in chron library) so I can do things like calculate the mean time etc. How can I do this?

My attempt is just do times(data column) but I get a decimal value.

sammuh
  • 41
  • 3
  • 12

2 Answers2

1

Just for simplification, I'll assume a data.frame with just a single column. Note that even though it displays as the correct time format, the underlying data is still a decimal value.

library("chron")

mydf <- data.frame(time = c("00:20:10", "02:12:10"), stringsAsFactors = FALSE)
mydf[] <- lapply(mydf,times)

mydf
      time
1 00:20:10
2 02:12:10

str(mydf)

'data.frame':   2 obs. of  1 variable:
  $ time:Class 'times'  atomic [1:2] 0.014 0.0918
.. ..- attr(*, "format")= chr "h:m:s"
0
as.POSIXct('00:20:10', format='%H:%M:%S')

[1] "2016-06-23 00:20:10 EDT"

as.POSIXct('2:12:10', format='%H:%M:%S')

[1] "2016-06-23 02:12:10 EDT"

You can also specify date, by

as.POSIXct('06/23/2016 00:20:10', format='%m/%d/%Y %H:%M:%S')

[1] "2016-06-23 00:20:10 EDT"

BigDataScientist
  • 1,045
  • 5
  • 17
  • 37