R 函数,用于生成伪随机二进制序列,其中相同的数字不会连续出现两次以上

问题描述 投票:0回答:1
我希望能够生成一个(伪)随机二进制序列(例如,Rs 和 Ls 的序列,如 RLLRRLR),该序列是平衡的,以便同一项目不会在序列中连续出现两次以上,并且如果例如,我有一个 20 个序列,每个序列我得到 10 个。 R中有没有一个函数可以做这样的事情?

我尝试自己写一个这样的函数。这是尝试:

RL_seq <- function(n_L = 10, n_R = 10, max_consec = 2, initial_seq = NULL) { while(n_L > 0 | n_R > 0){ side <- sample(c("R", "L"), 1) if (side == "R" & n_R > 0 & length(grep("R", tail(initial_seq, max_consec))) != max_consec) { initial_seq <- append(initial_seq, side) n_R <- n_R - 1 } else if (side == "L" & n_L > 0 & length(grep("L", tail(initial_seq, max_consec))) != max_consec) { initial_seq <- append(initial_seq, side) n_L <- n_L - 1 } } print(initial_seq) } # The function does not stop with the following seed set.seed(1) RL_seq()
但是,代码是否卡住取决于机会。我还希望可以更改序列的规则(例如,允许 3 个连续的 R),但如果我触及参数,代码往往会中断。此时,如果我可以使用默认参数运行它并且不会卡住,我会很高兴。

我四处寻找但找不到答案。任何帮助表示赞赏。另外,我对编程比较陌生,而且是自学的,以前从未在堆栈溢出上发布过任何内容,所以我提前道歉。

r sequence
1个回答
0
投票
RL_seq <- function(n_L = 10, n_R = 10, max_consec = 2) { seq = c(rep("L", n_L), rep("R", n_R)) consec = max(rle(seq)[1]$lengths) while(consec > max_consec) { seq = sample(seq, length(seq), replace = FALSE) consec = max(rle(seq)[1]$lengths) } seq } RL_seq()
    
© www.soinside.com 2019 - 2024. All rights reserved.