w
您在每次迭代时都会覆盖,因此您只会w
在最后一次迭代中得到值。
如果您知道要洗牌多少次,那么使用for
循环比使用循环更好repeat
。
目前尚不清楚您是否要包含与s 和s 的向量w
的实际比较,deck
或者仅包含表示是否存在匹配项的向量。无论如何,这里有几个实现这两个的例子:0
1
shuffle <- function(deck, n) {
out <- logical(length = n)
shuf <- deck
for(i in seq_len(n)) {
shuf <- sample(shuf)
out[i] <- any(shuf == deck)
}
out <- as.numeric(out)
out
}
使用如下并产生:
> set.seed(42)
> deck <- 1:100
> (out <- shuffle(deck, 20))
[1] 0 1 1 1 1 0 1 0 0 1 1 0 1 1 1 1 0 1 0 1
deck
返回洗牌后的牌组之间的匹配位置的版本是:
shuffle2 <- function(deck, n) {
out <- matrix(NA, ncol = n, nrow = length(deck))
shuf <- deck
for(i in seq_len(n)) {
shuf <- sample(shuf)
out[,i] <- shuf == deck
}
out <- out + 0
out
}
如下使用并产生
> set.seed(42)
> deck <- 1:100
> (out2 <- shuffle2(deck, 20))
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11]
[1,] 0 0 0 0 0 0 0 0 0 0 0
[2,] 0 0 0 0 0 0 0 0 0 0 0
[3,] 0 0 0 0 0 0 0 0 0 0 0
[4,] 0 0 0 0 0 0 0 0 0 0 0
[5,] 0 0 0 0 0 0 0 0 0 0 0
[6,] 0 0 0 0 0 0 0 0 0 0 0
[7,] 0 0 0 0 0 0 0 0 0 0 0
[8,] 0 0 0 0 0 0 0 0 0 0 0
[9,] 0 0 0 0 0 0 0 0 0 0 0
[10,] 0 0 0 1 0 0 0 0 0 0 0
....
该匹配矩阵很容易处理以产生任何匹配或不匹配的向量:
> as.numeric(apply(out2 > 0, 2, any))
[1] 0 1 1 1 1 0 1 0 0 1 1 0 1 1 1 1 0 1 0 1
与 给出的匹配shuffle()
。
您当然可以将两者结合起来,并由函数返回:
shuffle3 <- function(deck, n) {
out <- matrix(NA, ncol = n, nrow = length(deck))
shuf <- deck
for(i in seq_len(n)) {
shuf <- sample(shuf)
out[,i] <- shuf == deck
}
out <- list(matches = out+0,
summary = as.numeric(apply(out > 0, 2, any)))
out
}
用作并产生:
> set.seed(42)
> deck <- 1:100
> out3 <- shuffle3(deck, 20)
> str(out3)
List of 2
$ matches: num [1:100, 1:20] 0 0 0 0 0 0 0 0 0 0 ...
$ summary: num [1:20] 0 1 1 1 1 0 1 0 0 1 ...
> out3$summary
[1] 0 1 1 1 1 0 1 0 0 1 1 0 1 1 1 1 0 1 0 1
请注意,无论我使用哪个版本,我都会先创建一个对象来保存所需大小的结果,然后在循环中填充该对象。