gpt4 book ai didi

r - 在 R 中没有重复组星座的子组中对多个个体进行采样

转载 作者:行者123 更新时间:2023-12-03 20:23:02 25 4
gpt4 key购买 nike

我有多个individuals我想 - 随机 - 分成大小为 groupsize 的子组.这个过程我要重复一遍n_group次 - 没有重复的群星座。
我怎样才能在 R 中实现这一点?

到目前为止,我尝试了以下方法:

set.seed(1)
individuals <- 1:6
groupsize <- 3
n_groups <- 4

for(i in 1:n_groups) { print(sample(individuals, groupsize))}

[1] 1 4 3
[1] 1 2 6
[1] 3 2 6
[1] 3 1 5
..但我不确定这是否真的不会导致重复星座..?

编辑:在查看我意识到的第一个建议和答案之后,另一个限制对我来说可能很有趣(抱歉没有预先看到它......)。
是否(在上面的具体示例中)有一种方法可以确保每个人都与其他人保持联系?

最佳答案

根据您编辑的问题,我假设您想确保所有个体都至少属于一个子组?
那么这可能是解决方案:

individuals <- 1:6
groupsize <- 3
n_groups <- 4

#sample groups
library(RcppAlgos)
#initialise
answer <- matrix()
# If the length of all unique elements in the answer is smaller than
# the number of individuals, take a new sample
while (length(unique(as.vector(answer))) < length(individuals)) {
answer <- comboSample(individuals, groupsize, n = n_groups)
# Line below isfor demonstration only
#answer <- comboSample(individuals, groupsize, n = n_groups, seed = 123)
}
# sample answer with seed = 123 (see commented line above)
# [,1] [,2] [,3]
# [1,] 1 3 4
# [2,] 1 3 6
# [3,] 2 3 5
# [4,] 2 3 4
测试不包含每个人的组
# Test with the following matrix
# [,1] [,2] [,3]
# [1,] 1 2 3
# [2,] 1 3 4
# [3,] 1 4 5
# [4,] 2 3 4
# Note that individual '6' is not present
answer <- matrix(c(1,2,3,1,3,4,1,4,5,2,3,4), nrow = 4, ncol = 3)
while (length(unique(as.vector(answer))) < length(individuals)) {
answer <- comboSample(individuals, groupsize, n = n_groups)
}
# is recalculated to (in this case) the following answer
# [,1] [,2] [,3]
# [1,] 4 5 6
# [2,] 3 4 5
# [3,] 1 3 6
# [4,] 2 4 5
通过;-)

关于r - 在 R 中没有重复组星座的子组中对多个个体进行采样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67386742/

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