Recognize time in R

2020-04-21 05:08发布

问题:

I am working on a dataset in R with a time variable like this:

Time = data.frame("X1"=c(930,1130,914,1615))

The first one/two digits of X1 refers to hour and the last two refers to minute. I want to make R recognize it as a time variable.

I try to use lubridate hm function but it didnt work probably because a ":" is missing between the hour and minute in my data.

I also thought about using str_sub function to separate the hour and minute first and then put them together with a ":" in between and finally use the lubridate function but I dont know how to extract the hour since sometimes it is presented as one digit but sometimes it is presented as two digits.

How do I make R recognize this as a time variable? Thanks very much!

回答1:

You could 0-pad to 4 digits and then format using standard R date tools:

as.POSIXct(sprintf("%04d",Time$X1), format="%H%M")
#[1] "2018-04-22 09:30:00 AEST" "2018-04-22 11:30:00 AEST"
#[3] "2018-04-22 09:14:00 AEST" "2018-04-22 16:15:00 AEST


回答2:

This converts them to chron "times" class. Internally such variables are stored as a fraction of a day and are rendered on output as shown below. The sub inserts a : before the last 2 characters and :00 after them so that they are in HH:MM:SS format which times understands.

library(chron)

times(sub("(..)$", ":\\1:00", Time$X1))
## [1] 09:30:00 11:30:00 09:14:00 16:15:00

It could also be done like this where we transform each to a fraction of a day:

with(Time, times( (X1 %/% 100) / 24 + (X1 %% 100) / (24 * 60) ))
## [1] 09:30:00 11:30:00 09:14:00 16:15:00