For Loop 根据条件从不同的列表中采样

For Loop to sample from a different list based on condition

我有这样的数据:

List_of_lists = list("0" = list(4,6), "1" = list(6,8), "2" = list(7,9), 
                     "3" = list(4,8), "4" = list(3,9,0), "6" = list(1,7,0), 
                     "7" = list(2,6), "8" = list(1,3), "9" = list(2,4))

我想编写一个迭代函数,它首先从 List_of_Moves 的第一个索引(即“0”)中采样,对于后续迭代,从名称与前一个匹配的不同列表中采样迭代的结果。换句话说,如果第一次迭代的结果是 4,那么我会从名称为“4”的列表中采样 - 依此类推。

在 "Hack-n-Slash" R 形式中,它看起来像这样:

> sample(unlist(List_of_lists"0",1,replace=TRUE)
4
> sample(unlist(List_of_lists"4",1,replace=TRUE)
3
> sample(unlist(List_of_lists"3",1,replace=TRUE)
8
> sample(unlist(List_of_lists"8",1,replace=TRUE)
1
> sample(unlist(List_of_lists"1",1,replace=TRUE)
6

可能是这样的。我们从 List_of_lists 中采样一个元素,将其存储为结果并将其作为初始参数传递给下一轮,同时将大小减小 1 直到我们满足 size 标准我们 return NULL 并且迭代停止:

r_ge <- function(init = "0", size) {
    if(size == 0) NULL
    else {
        tmp <- sample(List_of_lists[[as.character(init)]], 1)
        c(unlist(tmp), r_ge(tmp, size - 1))
    }
}

用例:

r_ge(size = 5)
# [1] 4 9 2 9 2
r_ge(size = 5)
# [1] 6 1 8 1 6
r_ge(size = 5)
# [1] 6 0 4 9 4
r_ge(size = 5)
# [1] 4 9 4 0 4

或者,我相信这也能满足您的需求:

first_seed <- rbinom(n = 1, size = 9, prob = .5) # just to get a starting value
for (i in 1:20){
  first_seed <- sample(x = unlist(List_of_lists[[as.character(first_seed)]][]), 1)
  print(first_seed)
}

一些注意事项:rbinom() 不适合获取第一个值,但我将其留给您修改。此外,1:20 仅用于演示目的,显然可以根据需要增加或减少迭代次数。