Storing time without date, but not as a class
I have a local.time column in my class dataframe containing elements like this:
> a$local.time
[1] "1:30 AM" "6:29 AM" "6:59 AM" "9:54 AM" "10:14 AM" "10:34 AM" "12:54 PM" "1:15 PM" "1:20 PM"
[10] "1:20 PM" "2:15 PM" "2:15 PM" "4:23 AM" "6:28 AM" "2:45 PM" "3:08 PM" "3:23 PM" "3:58 PM"
I would like to convert them from class to time variables. So I used:
> as.POSIXct(a$local.time, tz = "", format = "%I:%M %p", usetz = FALSE)
The result was:
[1] "2014-10-31 01:30:00 EDT" "2014-10-31 06:29:00 EDT" "2014-10-31 06:59:00 EDT" "2014-10-31 09:54:00 EDT"
[5] "2014-10-31 10:14:00 EDT" "2014-10-31 10:34:00 EDT" "2014-10-31 12:54:00 EDT" "2014-10-31 13:15:00 EDT"
I have a date variable in another column and we intend to provide the ability to filter by date and scale by time ranges per minute in a dynamic panel.
I want to remove the date and timezone from $ local.time, but keep it in time format to keep the chronology, i.e. 18:57 is the 19th and 57th minutes of the day, etc.
If i use
a$local.time <- format(a$local.time, "%Y-%m-%d %H:%M:%S", usetz = FALSE)
a$local.time <- strftime(a$local.time, format = "%H:%m")
,
class changes to symbol! What's the correct approach?
source to share
The package chron
has a class "times" that you might find useful. Starting with something similar to what you have so far:
x <- c("1:30 AM", "6:29 AM", "6:59 AM", "9:54 AM", "10:14 AM", "3:15 PM"))
a <- as.POSIXct(x, tz = "", format = "%I:%M %p", usetz = FALSE)
Then we can use the function times
withformat
library(chron)
(tms <- times(format(a, "%H:%M:%S")))
# [1] 01:30:00 06:29:00 06:59:00 09:54:00 10:14:00 15:15:00
attributes(tms)
# $format
# [1] "h:m:s"
#
# $class
# [1] "times"
source to share
You can use a number of functions hms
(hour-minute-second) in a package lubridate
.
library(lubridate)
times = c("1:30 AM", "6:29 AM", "6:59 AM", "9:54 AM", "2:45 PM")
I was hoping that you can just do:
hm(times)
[1] "1H 30M 0S" "6H 29M 0S" "6H 59M 0S" "9H 54M 0S" "2H 45M 0S"
But note that it hm
does not recognize the AM / PM distinction. So here's a more complex method that requires first use strptime
, which recognizes AM / PM and then returns the result in a form hm
.
hm(paste0(hour(strptime(times, "%I:%M %p")),":",
minute(strptime(times, "%I:%M %p"))))
[1] "1H 30M 0S" "6H 29M 0S" "6H 59M 0S" "9H 54M 0S" "14H 45M 0S"
Probably the best way, but it works.
UPDATE: To answer your comment, you can use the functions hour
and minute
to get the hours and minutes (although I like @RichardScriven better). For example:
hour(times)
[1] 1 6 6 9 14
mean(hour(times) + minute(times)/60)
[1] 7.923333
source to share