Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting numbers to time

Tags:

time

r

I entered my data by hand, and to save time I didn't include any punctuation in my times. So, for example, 8:32am I entered as 832. 3:34pm I entered as 1534. I'm trying to use the 'chrono' package (http://cran.r-project.org/web/packages/chron/chron.pdf) in R to convert these to time format, but chrono seems to require a delimiter between the hour and minute values. How can I work around this or use another package to convert my numbers into times?

And if you'd like to criticize me for asking a question that's already been answered before, please provide a link to said answer, because I've searched and haven't been able to find it. Then criticize away.

like image 903
filups21 Avatar asked Jan 08 '14 18:01

filups21


3 Answers

I think you don't need the chron package necessarily. When:

x  <-  c(834, 1534)

Then:

time <- substr(as.POSIXct(sprintf("%04.0f", x), format='%H%M'), 12, 16)
time

[1] "08:34" "15:34"

should give you the desired result. When you also want to include a variable which represents the date, you can use the ollowing line of code:

df$datetime <- as.POSIXct(paste(df$yymmdd, sprintf("%04.0f", df$x)), format='%Y%m%d %H%M%S')
like image 100
Jaap Avatar answered Oct 11 '22 00:10

Jaap


Here's a sub solution using a regular expression:

set.seed(1); times <- paste0(sample(0:23,10), sample(0:59,10)) # ex. data
sub("(\\d+)(\\d{2})", "\\1:\\2", times) # put in delimitter
# [1] "6:12"  "8:10"  "12:39" "19:21" "4:43"  "17:27" "18:38" "11:52" "10:19" "0:57" 
like image 4
lukeA Avatar answered Oct 11 '22 01:10

lukeA


Say

x  <-  c('834', '1534')

The last two characters represent minutes, so you can extract them using

mins  <-  substr(x, nchar(x)-1, nchar(x))

Similarly, extract hours with

hour  <-  substr(x, 0, nchar(x)-2)

Then create a fixed vector of time values with

time  <-  paste0(hour, ':', mins)

I think you are forced to specify dates in the chron package, so assuming a date value, you can converto chron with this:

chron(dates.=rep('02/02/02', 2), 
      times.=paste0(hour, ':', mins, ':00'), 
      format=c(dates='m/d/y',times='h:m:s'))
like image 2
JAponte Avatar answered Oct 11 '22 00:10

JAponte