How to sample dates of the same weekday?

92 views Asked by At

Considering the date samples:

t_s<-seq(as.POSIXct("2010-01-01 00:00:00"), as.POSIXct("2010-12-31 23:00:00"), by = '1 day')

and a date vector:

t<-seq(as.POSIXct("2010-02-01 00:00:00"), as.POSIXct("2010-2-10 23:00:00"), by = '1 day')

Now, I want to randomly sample dates in t_s with the same weekday of the elements in t.The sample size should be 4 for each t element. For example, the samples for the first element "2010-02-01" could be "2010-06-28" "2010-5-31" "2010-8-02" "2010-10-04" because they are all Monday.

The sampled dates from t_s maybe multipul, beacause some dates in t share a same weekday. However, if t_s is much smaller than t(not in the examplified case), the uniqueness of samples cannot be met. Therefore, sample methods with and without multipul t_s dates are both wanted.

How could I get these samples?

1

There are 1 answers

3
dimitris_ps On BEST ANSWER

Something like this should do what you need

Without replacement

lapply(seq_along(t), function(x){
  sample(t_s[weekdays(t_s)==weekdays(t[x])], 4, replace = FALSE)
})

With replacement

lapply(seq_along(t), function(x){
  sample(t_s[weekdays(t_s)==weekdays(t[x])], 4, replace = TRUE)
})

These return a list with your samples

Excluding previously selected dates

# Based on @lmo comment
ds <- c()
lapply(seq_along(t), function(x){
  if(x == 1){ result <- sample(t_s[weekdays(t_s)==weekdays(t[x])], 4)
} else {
  t_s2 <- t_s[!(t_s %in% ds)]
  result <- sample(t_s2[weekdays(t_s2)==weekdays(t[x])], 4)
}
ds <<- c(ds, result)
result
})