Search code examples
rdatesample

Get Random Days Based on the Month in R


I want to be able to generate random YYYMMDD variables

I tried:

Day=ifelse(substr(o1$Month,6,7) %in% c(1,3,5,7,8,10,12),sample(c(paste0('0',1:9),10:31),1),
           ifelse(substr(o1$Month,6,7) == 2,sample(c(paste0('0',1:9),10:28),1),sample(c(paste0('0',1:9),10:30),1))) 

to generate a random day based on the month. Note that o1$Month is of YYYY-MM format. But the results are all identical days.

> table(o1$Day)

25

55

Can anyone offer some advice so I can get other days as well.

Thanks


Solution

  • To create a random date you could use the following:

    gsub("-", "", sample(seq(as.Date("1900-01-01"), 
                             as.Date("2000-12-31"), 
                             by = "day"), 10))
    
    #[1] "19700214" "19910824" "19640205" "19531101" "19020116" "19360823" "19791019" "19520713" "19890408" "19220327"
    

    Here, I create a sequence of days between two dates (1900/01/01 and 2000/12/31) and then randomly sample from them 10 times. If you want unique dates, use this code. Otherwise, set replace = TRUE in the sample function. I then use gsub to replace the dashes with empty strings. For example, 1947-11-01 becomes 19471101. You can change the dates to sample from if you want a specific range.