带条件随机抽样两张数据表

Random sampling of two data tables with condition

我正在尝试根据条件对两个数据 table 进行采样,然后合并两个结果样本的列并复制这些步骤并将结果样本附加到新数据 table .两个table的摘录(它们没有样本长度):

data1
   month1 year
1: 1    2014
2: 2    2015
3: 3    2016
..

data2
   month2    
1: 4   
2: 5    
3: 6   
..

第一个样本: s1 = sample(data1[month = i ], 100, replace=TRUE) 其中 i 从 1 到 n

第二个样本: s2 = sample(data2[month > i ], 100, replace=TRUE) 其中 i 应大于为 s1 选择的月份。

这两个样本应该合并成一个新数据 table 就像 dt1 = cbind(s1,s2)

我想对每个月 i 重复这些步骤,并使用所有生成的样本(伪代码)创建一个新数据集:

 for(i in 1:10){
s1_i  = sample(data1[month = i ], 100, replace=TRUE)
s2_i = sample(data2[month > i ], 100, replace=TRUE)
new_i = cbind(s1_i,s2_i)
 }
allsamples = rbind(new_1,new_2,new_3,...)

我写这个循环有问题,它不应该为每一步都创建数据集,而应该只创建 allsamples 数据集,其中所有样本都被组合在一起。

这个怎么样?

allsamples <- NULL
for(i in 1:length(month)){
  s1 <- sample(data1[month == i], 100, replace = TRUE)
  s2 <- sample(data1[month > i], 100, replace = TRUE)
  allsamples <- rbind(allsamples, cbind(s1, s2))
}

根据设置,您正在使用 替换进行抽样,这是您打算做的吗?

可能有更好的方法来做到这一点,因为增长的对象通常很慢,但看到只有 12 个月的循环时间,我想这不会对您的性能造成太大影响。

这是我的解决方案:

  newsample =list()
  begin_time = 1 
  end_time = 20 
  for(i in  begin_time:end_time){
      datasub1 <-data1[data1$var == i,]  #filter data on condition
      s1 <-  datasub1[sample(nrow( datasub1), 10, replace=T), ]  #sample
      datasub2 <- data2[data2$var2 > i,]
      s2 <- datasub2[sample(nrow(datasub2), 10, replace=T), ]
      newsample[[i-(begin_time-1])] <- cbind(s1,s2) #combine and store in list
   }
 allsample = rbindlist(newsample) #stack samples as data table