Search code examples
rrandomtimesampling

Is there a way to generate just random "times"?


I know that you can use as.POSIXct to generate dates and times. But I want to generate just the times ex) 05:16 (min:sec) Does anyone know how to do it? I could not find any package for just time.


Solution

  • lubridate is currently the most friendly package to deal with times. Just generate the interval you need and sample from that:

    library(lubridate)
    
    > sample(as.duration(0:599), 30)
    [1] "345s (~5.75 minutes)" "277s (~4.62 minutes)" "74s (~1.23 minutes)" 
    [4] "15s"                  "571s (~9.52 minutes)" "186s (~3.1 minutes)" 
    [7] "45s"                  "355s (~5.92 minutes)" "121s (~2.02 minutes)"
    [10] "488s (~8.13 minutes)" "179s (~2.98 minutes)" "371s (~6.18 minutes)"
    [13] "515s (~8.58 minutes)" "31s"                  "346s (~5.77 minutes)"
    [16] "0s"                   "398s (~6.63 minutes)" "84s (~1.4 minutes)"  
    [19] "160s (~2.67 minutes)" "457s (~7.62 minutes)" "94s (~1.57 minutes)" 
    [22] "212s (~3.53 minutes)" "591s (~9.85 minutes)" "576s (~9.6 minutes)" 
    [25] "348s (~5.8 minutes)"  "314s (~5.23 minutes)" "563s (~9.38 minutes)"
    [28] "509s (~8.48 minutes)" "538s (~8.97 minutes)" "71s (~1.18 minutes)" 
    

    Check the functions interval() and ms() for other possible ways to get what you want.

    But as pointed out in the comments, if what you need is simply random intervals in seconds, it is simpler and more convenient to work with integers.