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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With