Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a random date with exceptions in R

Tags:

date

r

I want to create a random date variable given the time frame with exceptions in R. I was able to generate a random date:

random_date = sample(x = seq(from = as.Date("2022-01-01"),
                             to   = as.Date("2022-12-31"),
                             by   = 'day'),
                     size = 1)

Now, I want to filter the random date with exception dates:

exception_date = c(as.Date("2022-04-01"), as.Date("2022-08-01"), as.Date("2022-12-01"))

Is it possible to filter these given dates using the seq function, or should I use a different approach?

like image 514
jstaxlin Avatar asked Sep 02 '25 17:09

jstaxlin


1 Answers

You can subset your sequence using %in%:

exception_date <- c(as.Date("2022-04-01"), as.Date("2022-08-01"), as.Date("2022-12-01"))
time_seq <- seq(from = as.Date("2022-01-01"),
                to   = as.Date("2022-12-31"),
                by   = 'day')
time_seq <- time_seq[!time_seq %in% exception_date]
random_date <- sample(x = time_seq, size = 1)
like image 199
Clemsang Avatar answered Sep 05 '25 08:09

Clemsang