带条件的两个数据表的随机抽样

时间:2019-02-24 00:32:35

标签: r datatable sample

我试图在一个条件下对两个数据表进行采样,然后合并两个结果采样的列,并复制这些步骤,并将结果采样附加到新的数据表中。提取两个表(它们没有样本长度):

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选择的月份。

这两个样本应该合并到一个新的数据表中,例如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数据集。

2 个答案:

答案 0 :(得分:0)

怎么样?

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个月的循环时间,我想这不会对您的性能造成太大影响。

答案 1 :(得分:0)

这是我的解决方法:

  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
相关问题