Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the best practice of handling time in R?

Tags:

datetime

r

I am working with a survey dataset. It has two string vectors, start and finish, indicating the time of the day when the interview was started, and finished, respectively.

They are character strings that look like: "9:24 am", "12:35 pm", and so forth. I am trying to calculate the duration of the interview based on these two. What is the best way of doing this?

I know that, for dates, there are lots of classes or functions like as.date(), as.Date(), chron(), or as.POSIXct(). So I was looking for something like as.time(), but could not find it. Should I just append a made-up date and convert the whole thing into a POSIX() date-time class, then use difftime()?

What is the best practice of handling time in R?

like image 385
Chang Chung Avatar asked Feb 24 '09 17:02

Chang Chung


2 Answers

You need to use strptime() to convert the string to a date. For example:

strptime("9:24 am",format="%I:%M %p")

Then you can take differences just by taking one away from the other:

strptime("9:24 am",format="%I:%M %p")-strptime("12:14 am",format="%I:%M %p")
Time difference of 9.166667 hours

You can store this and then do an as.numeric() if you just want the number out, otherwise you can pass around the time objects.

Hope this helps!

like image 95
David Lawrence Miller Avatar answered Sep 28 '22 11:09

David Lawrence Miller


one option is to use regular expressions. if you are not familiar with them, they are used to parse strings using patterns. i would research regular expressions and then here are the functions in r

hope it helps

like image 24
Samuel Avatar answered Sep 28 '22 12:09

Samuel