我正在寻找生成多个随机字母列表,其中某个位置的字母重复出现。
这是“ 2-back”规则的示例。它是一个随机字母的列表,但有25%的时间与该字母前面的2个字母匹配。匹配的为1,不匹配的为0
R 0
Y 0
M 0
Y 1
L 0
C 0
F 0
G 0
S 0
G 1
我希望能够指定列表的长度以及实际上遵循该模式并重复的字母的百分比。其余字母将是随机生成的。
我不知道我是否已经很好地解释了这个问题。有人可以帮我这个忙吗?
答案 0 :(得分:1)
由于此过程取决于状态,因此我认为使用for
/ while
循环是一种罕见的情况,与其他方法相比,这通常很慢。您仍然想通过以矢量的总长度创建矢量来预先分配矢量。您可以执行以下操作:
total_length = 20
back_prob = 0.25
two_back_seq = character(total_length)
types = character(total_length)
# Generate the random results used to determine if we sample randomly
# or repeat the 2-back element
rolls = runif(total_length)
current_index = 1
while (current_index <= total_length) {
if ((rolls[current_index] > back_prob) || (current_index < 3)) {
two_back_seq[current_index] = sample(letters, 1)
types[current_index] = "random"
} else {
two_back_seq[current_index] = two_back_seq[current_index - 2]
types[current_index] = "two back"
}
current_index = current_index + 1
}
示例结果:
> two_back_seq
[1] "u" "x" "u" "b" "x" "w" "t" "w" "o" "b" "o" "l" "m" "m" "m" "u" "d" "t" "k" "t"
> types
[1] "random" "random" "two back" "random" "random" "random"
"random" "two back" "random" "random" "two back" "random" "random"
[14] "random" "two back" "random" "random" "random" "random" "random"
答案 1 :(得分:0)
假设您要为单个字母a
制作图案。首先生成一些字母,然后使用prob
设置字母的相对频率:
x <- sample(letters[1:5], 500, prob=c(.01,.09,.2,.3,.3), replace=TRUE)
现在插入额外的字母以间隔一定的时间来制作图案:
x <- ifelse(x[-1:-3]=="a", "a", x[seq(1,length(x)-3)])
有帮助吗?
(要检查哪些元素等于a
,我使用了which(x == "a")
)