具有替换的样本但约束每个要绘制的成员的最大频率

Tho*_*ore 6 random r sample

是否可以将sampleR中的函数扩展为不返回多于2的相同元素replace = TRUE?

假设我有一个列表:

l = c(1,1,2,3,4,5)
Run Code Online (Sandbox Code Playgroud)

要替换3个元素,我会这样做:

sample(l, 3, replace = TRUE)
Run Code Online (Sandbox Code Playgroud)

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

李哲源*_*李哲源 8

set.seed(0)
Run Code Online (Sandbox Code Playgroud)

基本思路是将采样替换为采样而无需替换.

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
Run Code Online (Sandbox Code Playgroud)

如果您希望不同的值出现不同的次数,我们可以做到

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
Run Code Online (Sandbox Code Playgroud)

我们可以调用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
Run Code Online (Sandbox Code Playgroud)

所有列中的计数符合c(2, 3, 3, 4, 1)我们设置的频率上限.


你能解释一下之间的区别rep和rep.int?

rep.int不是"整数"方法rep.它只是一个更快速的原始函数,功能更少rep.你可以得到更多的细节rep,rep.int并rep_len从文档页面?rep.