samedi 16 juillet 2016

R - For Loop to sample from a different list based on condition

I have data that looks like this:

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))

I'd like to write an iterative function that first samples from the first index of List_of_Moves (i.e. "0"), and for subsequent iterations, sample from a different list whose name matches with the previous iteration's result. In other words, if the first iteration's result is a 4, then I sample from the list whose name is "4" - and so on and so forth.

In "Hack-n-Slash" R form, it looks something like this:

> 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

Aucun commentaire:

Enregistrer un commentaire