converting numbers to time

后端 未结 5 520
小鲜肉
小鲜肉 2020-12-18 03:49

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

相关标签:
5条回答
  • 2020-12-18 03:54

    Here are two solutions that do not use regular expressions:

    library(chron)
    x <- c(832, 1534, 101, 110) # test data
    
    # 1
    times( sprintf( "%d:%02d:00", x %/% 100, x %% 100 ) )
    
    # 2
    times( ( x %/% 100 + x %% 100 / 60 ) / 24 )
    

    Either gives the following chron "times" object:

    [1] 08:32:00 15:34:00 01:01:00 01:10:00
    

    ADDED second solution.

    0 讨论(0)
  • 2020-12-18 03:59

    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')
    
    0 讨论(0)
  • 2020-12-18 04:02

    I thought I'd throw out a non-regex solution that uses lubridate. This is probably overkill.

    library(lubridate)
    library(stringr)
    
    time.orig <- c('834', '1534')
    
    # zero pad times before noon
    time.padded <- str_pad(time.orig, 4, pad="0")
    
    # parse using lubridate
    time.period <- hm(time.padded)
    
    # make it look like time
    time.pretty <- paste(hour(time.period), minute(time.period), sep=":")
    

    And you end up with

    > time.pretty
    [1] "8:34"  "15:34"
    
    0 讨论(0)
  • 2020-12-18 04:15

    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'))
    
    0 讨论(0)
  • 2020-12-18 04:16

    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" 
    
    0 讨论(0)
提交回复
热议问题