Skip to contents

Simulate a vector of random datetime values (class POSIXct). Provides the option of inserting NAs or returning base::NULL or zero-length datetimes.

Usage

sim_datetime(
  x = seq(from = as.POSIXct(Sys.Date() - 5), to = as.POSIXct(Sys.Date() + 5), by =
    "hour"),
  length = c(1, 10),
  prob_na = 0,
  n_na = 1L,
  prob_null = 0,
  prob_zero_length = 0,
  names = FALSE,
  replace = TRUE
)

Arguments

x

(class POSIXct vector)
The vector to randomly sample from.

length

(integer vector of length 1 or 2)
The number of elements in the simulated vector. If length(length)==1L, sets the number of elements to length. If length(length)==2L, randomly selects the number of elements from the interval [min, max].

prob_na

(Scalar numeric: [0, 1])
The probability of inserting an NA.

n_na

(Scalar integer: [0, Inf])
The number of NAs to insert.

prob_null

(Scalar numeric: [0, 1])
The probability of returning a NULL object.

prob_zero_length

(Scalar numeric: [0, 1])
The probability of returning a zero-length vector.

names

(Scalar logical: c(TRUE, FALSE))
Whether or not the vector should have names. TRUE (default) sets names as name_1, name_2, name_3, ...

replace

(Scalar logical: c(TRUE, FALSE))
Whether or not elements from x can be repeated in the result. TRUE (default) samples with replacement.

Value

POSIXct vector

Examples

#----------------------------------------------------------------------------
# sim_datetime() examples
#----------------------------------------------------------------------------
library(bkcheck)

sim_datetime()
#> [1] "2026-06-16 21:00:00 UTC" "2026-06-16 17:00:00 UTC"
#> [3] "2026-06-10 04:00:00 UTC" "2026-06-11 23:00:00 UTC"
#> [5] "2026-06-18 14:00:00 UTC" "2026-06-13 20:00:00 UTC"
#> [7] "2026-06-17 20:00:00 UTC" "2026-06-16 00:00:00 UTC"
#> [9] "2026-06-12 08:00:00 UTC"
sim_datetime(prob_na = 1)
#> [1] "2026-06-13 02:00:00 UTC" "2026-06-14 12:00:00 UTC"
#> [3] "2026-06-16 11:00:00 UTC" "2026-06-12 19:00:00 UTC"
#> [5] "2026-06-18 05:00:00 UTC" NA                       
sim_datetime(prob_null = 1)
#> NULL
sim_datetime(prob_zero_length = 1)
#> POSIXct of length 0
sim_datetime(names = TRUE)
#>                    name_1                    name_2                    name_3 
#> "2026-06-09 15:00:00 UTC" "2026-06-17 05:00:00 UTC" "2026-06-17 20:00:00 UTC" 
#>                    name_4                    name_5 
#> "2026-06-19 00:00:00 UTC" "2026-06-16 12:00:00 UTC"