s<-data.frame(DateTime=seq(as.POSIXct("2016-11-02 10:40:00"), by="sec", length.out=100), FileName=paste0(rep("file-",100), 1:100))
window<-20
sampleSize <-5
groups<-seq(1, nrow(s), by=window) #indexes of first element in each window
result<-lapply(groups, function(x) s[sample(x:(x+window-1), sampleSize), "FileName"]) #for each group, randomly select sampleSize number of elements
编辑:按时间间隔分割
s<-data.frame(DateTime=as.POSIXct("2016-11-02 10:40:00") + sample(1:200, 100, replace = T))
s$FileName<-paste0("file-",rownames(s),"-",format(s$DateTime, "%H%M%S"))
s<-s[order(s$DateTime ),] #Order date time from old to recent
sampleSize <-5
window.sec<- 25
split <- seq(min(s$DateTime), max(s$DateTime), by=(window.sec+1)) # splitting into groups
#[1] "2016-11-02 10:40:02 MYT" "2016-11-02 10:40:28 MYT" "2016-11-02 10:40:54 MYT" "2016-11-02 10:41:20 MYT" "2016-11-02 10:41:46 MYT"
#[6] "2016-11-02 10:42:12 MYT" "2016-11-02 10:42:38 MYT" "2016-11-02 10:43:04 MYT"
groups<- c( sapply(split, function(x) min(which(s$DateTime>=x))) , nrow(s)) #indexes of first element in each group, and include the last index.
#The first element in each group can be more recent than that in the split, if x is n.
# > s[groups,]
# DateTime FileName
# 56 2016-11-02 10:40:02 file-56-104002
# 53 2016-11-02 10:40:30 file-53-104030
# 60 2016-11-02 10:40:56 file-60-104056
# 95 2016-11-02 10:41:20 file-95-104120
# 81 2016-11-02 10:41:46 file-81-104146
# 57 2016-11-02 10:42:12 file-57-104212
# 39 2016-11-02 10:42:39 file-39-104239
# 59 2016-11-02 10:43:04 file-59-104304
# 75 2016-11-02 10:43:20 file-75-104320
result<-lapply(1:(length(groups)-1), function(i) s[sample(groups[i]:(groups[i+1]-1), sampleSize), "FileName"])
names(result) <- as.character(split)