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!
You could 0-pad to 4 digits and then format using standard R date tools:
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. Thesub
inserts a:
before the last 2 characters and:00
after them so that they are in HH:MM:SS format whichtimes
understands.It could also be done like this where we transform each to a fraction of a day: