gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 14:22:36 25 4
gpt4 key购买 nike

是否可以扩展 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com