Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Generating a random date with exceptions in 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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading