Recognize time in R

一世执手 提交于 2019-12-02 12:03:45

问题


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


来源:https://stackoverflow.com/questions/49961191/recognize-time-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!