Home > Software engineering >  Generating a random date with exceptions in R
Generating a random date with exceptions in R

Time:12-15

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?

CodePudding user response:

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)

CodePudding user response:

You can not filter in the seq()-function, but you can use setdiff() to exclude the exception dates in the sample()function. The only problem is that setdiff() transforms the result into numeric and you have to transform it back to Date.

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

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