如何采样同一工作日的日期?
How to sample dates of the same weekday?
考虑日期样本:
t_s<-seq(as.POSIXct("2010-01-01 00:00:00"), as.POSIXct("2010-12-31 23:00:00"), by = '1 day')
和一个日期向量:
t<-seq(as.POSIXct("2010-02-01 00:00:00"), as.POSIXct("2010-2-10 23:00:00"), by = '1 day')
现在,我想随机抽样 t_s
中的日期与 t
中元素的同一工作日。每个 t
元素的样本大小应为 4。
例如,第一个元素 "2010-02-01"
的样本可能是 "2010-06-28" "2010-5-31" "2010-8-02" "2010-10-04"
,因为它们都是星期一。
t_s
中的采样日期可能是多个日期,因为 t
中的某些日期共享同一工作日。但是,如果t_s
远小于t
(示例中不是),则无法满足样本的唯一性。因此,具有和不具有多重 t_s
日期的示例方法都是需要的。
我怎样才能得到这些样本?
像这样的东西应该可以满足您的需要
无需更换
lapply(seq_along(t), function(x){
sample(t_s[weekdays(t_s)==weekdays(t[x])], 4, replace = FALSE)
})
有替换
lapply(seq_along(t), function(x){
sample(t_s[weekdays(t_s)==weekdays(t[x])], 4, replace = TRUE)
})
这些 return 包含您的样本的列表
不包括之前选择的日期
# 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
})
考虑日期样本:
t_s<-seq(as.POSIXct("2010-01-01 00:00:00"), as.POSIXct("2010-12-31 23:00:00"), by = '1 day')
和一个日期向量:
t<-seq(as.POSIXct("2010-02-01 00:00:00"), as.POSIXct("2010-2-10 23:00:00"), by = '1 day')
现在,我想随机抽样 t_s
中的日期与 t
中元素的同一工作日。每个 t
元素的样本大小应为 4。
例如,第一个元素 "2010-02-01"
的样本可能是 "2010-06-28" "2010-5-31" "2010-8-02" "2010-10-04"
,因为它们都是星期一。
t_s
中的采样日期可能是多个日期,因为 t
中的某些日期共享同一工作日。但是,如果t_s
远小于t
(示例中不是),则无法满足样本的唯一性。因此,具有和不具有多重 t_s
日期的示例方法都是需要的。
我怎样才能得到这些样本?
像这样的东西应该可以满足您的需要
无需更换
lapply(seq_along(t), function(x){
sample(t_s[weekdays(t_s)==weekdays(t[x])], 4, replace = FALSE)
})
有替换
lapply(seq_along(t), function(x){
sample(t_s[weekdays(t_s)==weekdays(t[x])], 4, replace = TRUE)
})
这些 return 包含您的样本的列表
不包括之前选择的日期
# 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
})