[英]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.