gpt4 book ai didi

r - 在 R 中创建多对

转载 作者:行者123 更新时间:2023-12-02 00:10:44 27 4
gpt4 key购买 nike

我有一份人员名单:

people<-c("Betty", "Joe", "Bob", "Will", "Frank")

我想给每个人随机分配两个人(不允许自己分配)并且我希望每个人被分配给另一个人的次数相等(在上面的例子中,每个人只能被分配给又两次)。

例如,匹配可以是

贝蒂(乔和鲍勃)、乔(鲍勃和威尔)、鲍勃(威尔和弗兰克)、威尔(弗兰克和贝蒂)

当然,我刚刚使用了他们的顺序,但如果可以随机化就更好了。

有什么想法可以从哪里开始?

最佳答案

新的(更简单的)解决方案:使用 Ari B. Friedman 的 TaRifx 包中的 shift 函数

tt <- sample(people)
lapply(seq_len(length(tt))-1, function(x) shift(tt, x)[1:3])
# if you don't want it to be ordered, just add a sample(.)
lapply(seq_len(length(tt))-1, function(x) sample(shift(tt, x)[1:3]))
# [[1]]
# [1] "Bob" "Frank" "Betty"
#
# [[2]]
# [1] "Frank" "Betty" "Joe"
#
# [[3]]
# [1] "Betty" "Joe" "Will"
#
# [[4]]
# [1] "Joe" "Will" "Bob"
#
# [[5]]
# [1] "Will" "Bob" "Frank"

旧的解决方案(对于这个想法):我会走这条路。基本上,一旦你采样“人”,你就可以总是去,1,2,3,2,3,4,3,4,5,4,5, 1.那么,让我们这样做吧。也就是说,生成这些指数,然后对人进行抽样并获得三胞胎。

# generate index
len <- length(people)
choose <- 3 # at a time
idx <- outer(seq(choose), seq(choose+2)-1, '+')
# [,1] [,2] [,3] [,4] [,5]
# [1,] 1 2 3 4 5
# [2,] 2 3 4 5 6
# [3,] 3 4 5 6 7

# sample people
tt <- sample(people)
# [1] "Joe" "Will" "Bob" "Frank" "Betty"
max.idx <- 2*choose + 1
tt[(len+1):max.idx] <- tt[seq(max.idx-len)]
# [1] "Joe" "Will" "Bob" "Frank" "Betty" "Joe" "Will"

tt[idx]
# [1] "Joe" "Will" "Bob" "Will" "Bob" "Frank" "Bob" "Frank" "Betty" "Frank"
# [15] "Betty" "Joe" "Betty" "Joe" "Will"

split(tt[idx], gl(ncol(idx), nrow(idx)))
# $`1`
# [1] "Joe" "Will" "Bob"
#
# $`2`
# [1] "Will" "Bob" "Frank"
#
# $`3`
# [1] "Bob" "Frank" "Betty"
#
# $`4`
# [1] "Frank" "Betty" "Joe"
#
# $`5`
# [1] "Betty" "Joe" "Will"

现在我们可以把这一切放在一个函数中:

my_sampler <- function(x, choose) {
len <- length(x)
idx <- outer(seq(choose), seq(choose+2)-1, '+')
sx <- sample(x)
max.idx <- 2*choose + 1
sx[(len+1):max.idx] <- sx[seq(max.idx-len)]
split(sx[idx], gl(ncol(idx), nrow(idx)))
}
# try it out
my_sampler(people, 3)
my_sampler(people, 4) # 4 at a time

# if you want this and want a non-ordered solution, wrap this with `lapply` and `sample`

lapply(my_sampler(people, 3), sample)

关于r - 在 R 中创建多对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15573311/

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