Take sample from diminishing population

I would like to take a random sample of rows from a data.frame, apply a function to the subset, then take a sample from the remaining rows, apply the function to the new subset (with different parameters), and so on.

A simple example would be if 5% of a population dies each month, in month 2 I need the population minus those ones who died in time month 1.

I have put together a very verbose method of doing this involving where I save the IDs from the sampled rows, then subset them out from the data for the second period, etc.

library(data.table)
dt <- data.table(Number=1:100, ID=paste0("A", 1:100))


first<-dt[sample(nrow(dt), nrow(dt)*.05)]$ID
mean(dt[ID %in% first]$Number)


second<-dt[!(ID %in% first)][sample(nrow(dt[!(ID %in% first)]),
                                 nrow(dt[!(ID %in% first)])*.05)]$ID
mean(dt[ID %in% c(first,second)]$Number)

dt[!(ID %in% first)][!(ID %in% second)] #...

Obviously, this is not sustainable past a couple periods. What is the better way to do this? I imagine this is a standard method but couldn't think what to look for specifically. Thanks for any and all input.


This shows how to "grow" a vector of items that have been sampled at a 5% per interval time course:

 removed <- numeric(0)
 for ( i in 1:10){ 
    removed <- c(removed, sample( (1:100)[!(1:100) %in% removed], # items out so far
                                  (100-length(removed))*.05))  # 5% of remainder
     cat(c(removed, "n"))  # print to console with each iteration.
     }
54 1 76 96 93 
54 1 76 96 93 81 16 13 79 
54 1 76 96 93 81 16 13 79 80 74 30 29 
54 1 76 96 93 81 16 13 79 80 74 30 29 52 33 86 19 
54 1 76 96 93 81 16 13 79 80 74 30 29 52 33 86 19 34 32 41 62 
54 1 76 96 93 81 16 13 79 80 74 30 29 52 33 86 19 34 32 41 62 5 70 8 
54 1 76 96 93 81 16 13 79 80 74 30 29 52 33 86 19 34 32 41 62 5 70 8 66 82 50 
54 1 76 96 93 81 16 13 79 80 74 30 29 52 33 86 19 34 32 41 62 5 70 8 66 82 50 6 91 99 
54 1 76 96 93 81 16 13 79 80 74 30 29 52 33 86 19 34 32 41 62 5 70 8 66 82 50 6 91 99 46 27 51 
54 1 76 96 93 81 16 13 79 80 74 30 29 52 33 86 19 34 32 41 62 5 70 8 66 82 50 6 91 99 46 27 51 22 23 20 

Notice that the actual number of items added to the list of "removals" will be decreasing.

链接地址: http://www.djcxy.com/p/73902.html

上一篇: 这是什么操作员

下一篇: 从减少人口中抽取样本