Search code examples
rdatetimeposixctnoise

Add random noise to POSIXct variable


I am modelling a Poisson point process and the times in my data are in the POSIXct form and are only accurate to the second. Thus, there are some times that are the same. I want to add some noise to these times so hopefully, they can be different. Is there any package or function in R that allows me to do that?


Solution

  • As Rui points out, this is largely a matter of formatting. I think the simplest way to do this is to allow fractions of seconds to be printed when you are working with POSIXct - you can do this with:

     options(digits.secs = 3)
    

    So now if I have a vector of times:

    times <- as.POSIXct(c("2020-07-11 13:06:01", "2020-07-11 13:06:01"))
    times
    #> [1] "2020-07-11 13:06:01 GMT" "2020-07-11 13:06:01 GMT"
    

    I can add fractions of seconds quite easily using the lubridate package:

    library(lubridate)
    
    times + seconds(runif(2))
    #> [1] "2020-07-11 13:06:01.494 GMT" "2020-07-11 13:06:01.470 GMT"
    

    In your case you probably want to add seconds(runif(length(times), -0.5, 0.5)) to keep your times randomized to within the nearest second.