r - 带有替换的样本,但限制了每个成员的最大绘制频率

标签 r random sample

是否可以扩展 sample R 中的函数在 replace = TRUE 时返回的相同元素不超过 2 个?

假设我有一个列表:

l = c(1,1,2,3,4,5)

要对 3 个元素进行替换采样,我会这样做:
sample(l, 3, replace = TRUE)

有没有办法限制它的输出,以便最多只返回 2 个相同的元素?所以(1,1,2)(1,3,3)是允许的,但是 (1,1,1)(3,3,3)被排除在外?

最佳答案

set.seed(0)

基本思想是将有放回抽样转换为无放回抽样。
ll <- unique(l)          ## unique values
#[1] 1 2 3 4 5
pool <- rep.int(ll, 2)   ## replicate each unique so they each appear twice
#[1] 1 2 3 4 5 1 2 3 4 5
sample(pool, 3)          ## draw 3 samples without replacement
#[1] 4 3 5

## replicate it a few times
## each column is a sample after out "simplification" by `replicate`
replicate(5, sample(pool, 3))
#     [,1] [,2] [,3] [,4] [,5]
#[1,]    1    4    2    2    3
#[2,]    4    5    1    2    5
#[3,]    2    1    2    4    1

如果您希望不同的值出现不同的次数,例如,我们可以这样做
pool <- rep.int(ll, c(2, 3, 3, 4, 1))
#[1] 1 1 2 2 2 3 3 3 4 4 4 4 5

## draw 9 samples; replicate 5 times
oo <- replicate(5, sample(pool, 9))
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    5    1    4    3    2
# [2,]    2    2    4    4    1
# [3,]    4    4    1    1    1
# [4,]    4    2    3    2    5
# [5,]    1    4    2    5    2
# [6,]    3    4    3    3    3
# [7,]    1    4    2    2    2
# [8,]    4    1    4    3    3
# [9,]    3    3    2    2    4

我们可以调用tabulate在每一列上计算 1, 2, 3, 4, 5 的频率:
## set `nbins` in `tabulate` so frequency table of each column has the same length
apply(oo, 2L, tabulate, nbins = 5)
#     [,1] [,2] [,3] [,4] [,5]
#[1,]    2    2    1    1    2
#[2,]    1    2    3    3    3
#[3,]    2    1    2    3    2
#[4,]    3    4    3    1    1
#[5,]    1    0    0    1    1

所有列中的计数满足频率上限c(2, 3, 3, 4, 1)我们已经设置了。

Would you explain the difference between rep and rep.int?


rep.int不是 rep 的“整数”方法.它只是一个比 rep 功能更少的更快的原始函数。 .您可以获取更多详情rep , rep.intrep_len来自文档页面 ?rep .

关于r - 带有替换的样本,但限制了每个成员的最大绘制频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52582802/

相关文章:

regex - 如何替换数据框中的字母?

c# - 生成一个 7 位数的数字,前面可以有零

c - 在 C 中组队并对抗随机化器

perl - 如何随机采样文件的内容?

mysql - 如何让示例代码工作?

r - 将变量值转换为列名; tidyr::spread 中的 "duplicate identifiers for rows"

r - 如何在 igraph 中对社区集群内的边缘进行着色

r - 我可以避免向量中的操作的 for 循环吗?

r - 从数据帧子集中对因子变量进行有效采样

java - java ADT中生成0到7的随机数,每个数字出现2次