sample_time: Draw a sample of n random times (from a given range).

View source: R/data_fun.R

sample_timeR Documentation

Draw a sample of n random times (from a given range).

Description

sample_time draws a sample of n random times from a given range.

Usage

sample_time(
  from = "1970-01-01 00:00:00",
  to = Sys.time(),
  size = 1,
  as_POSIXct = TRUE,
  tz = "",
  ...
)

Arguments

from

Earliest date-time (as string). Default: from = "1970-01-01 00:00:00" (as a scalar).

to

Latest date-time (as string). Default: to = Sys.time() (as a scalar).

size

Size of time samples to draw. Default: size = 1.

as_POSIXct

Boolean: Return calendar time ("POSIXct") object? Default: as_POSIXct = TRUE. If as_POSIXct = FALSE, a local time ("POSIXlt") object is returned (as a list).

tz

Time zone. Default: tz = "" (i.e., current system time zone, see Sys.timezone()). Use tz = "UTC" for Universal Time, Coordinated.

...

Other arguments. (Use for specifying replace, as passed to sample().)

Details

By default, sample_time draws n = 1 random calendar time (as a "POSIXct" object) in the range from = "1970-01-01 00:00:00" to = Sys.time() (current time).

Both from and to currently need to be scalars (i.e., with a length of 1).

If as_POSIXct = FALSE, a local time ("POSIXlt") object is returned (as a list).

The tz argument allows specifying time zones (see Sys.timezone() for current setting and OlsonNames() for options.)

Value

A vector of class "POSIXct" or "POSIXlt".

See Also

Other sampling functions: coin(), dice_2(), dice(), sample_char(), sample_date()

Examples

# Basics:
sample_time()
sample_time(size = 10)

# Specific ranges:
sort(sample_time(from = (Sys.time() - 60), size = 10))  # within last minute
sort(sample_time(from = (Sys.time() - 1 * 60 * 60), size = 10))  # within last hour
sort(sample_time(from = Sys.time(), to = (Sys.time() + 1 * 60 * 60), 
     size = 10, replace = FALSE))  # within next hour
sort(sample_time(from = "2020-12-31 00:00:00 CET", to = "2020-12-31 00:00:01 CET",
                 size = 10, replace = TRUE))  # within 1 sec range 
                           
# Local time (POSIXlt) objects (as list):
(lt_sample <- sample_time(as_POSIXct = FALSE))
unlist(lt_sample)

# Time zones:
sample_time(size = 3, tz = "UTC")
sample_time(size = 3, tz = "America/Los_Angeles")
 
# Note: Oddity with sample(): 
sort(sample_time(from = "2020-12-31 00:00:00 CET", to = "2020-12-31 00:00:00 CET",
     size = 10, replace = TRUE))  # range of 0!
# see sample(9:9, size = 10, replace = TRUE)


ds4psy documentation built on Sept. 15, 2023, 9:08 a.m.