我有一个人的名单:

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

我想随机分配两个人给每个人(不允许自我分配),我希望每个人分配给另一个人的次数相同(在上面的例子中,每个人只能分配给另一个人两次) .

因此,例如匹配可能是

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

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

任何想法从哪里开始?

最佳答案

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

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"

旧解决方案(对于想法):
我会走这条路。基本上,一旦你 sample "people",你总是可以去,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/

10-12 17:19