[英]Memory efficient way to sample from a vector of counts without replacement
在這里,我使用顏色頻率矢量表示一罐大理石
marbleCounts <- c(red = 5, green = 3, blue = 2)
marbleCounts
red green blue
5 3 2
現在,我想從此向量中采樣5個大理石,而無需替換。 通過將頻率向量擴展為大理石向量,然后從中進行采樣,可以做到這一點。
set.seed(2019)
marbles <- rep(names(marbleCounts), times = marbleCounts)
samples <- sample(x = marbles, size = 5, replace = FALSE)
table(samples)
green red
2 3
但這是內存效率低下(也許是性能低下嗎?)。 是否有一種更快和/或更有效的方式來采樣數據?
我認為這對您有用。
marbleCounts <- c(red = 5, green = 3, blue = 2)
# first, draw from the possible indexes (does not create the full vector)
draw <- sample.int(sum(marbleCounts), 5)
# then assign indexes back to original group
items <- findInterval(draw-1, c(0, cumsum(marbleCounts)), rightmost.closed = TRUE)
#extract your sample
obs <- names(marbleCounts)[items]
table(obs)
這將永遠不會創建超過樣本大小的向量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.