Lucasaudati11
Lucasaudati11

Reputation: 577

Random extraction from a list with NO REPLACEMENT

So I am wondering how to extract randomly a string from a list in R with NO REPLACEMENT till the list is empty. To write

sample(x, size=1, replace=FALSE)

is not helping me, since string are extracted more than once before the list gets empty.

Kind regards

Upvotes: 0

Views: 260

Answers (2)

quartin
quartin

Reputation: 451

In every iteration one list element will be picked, and from this element a value removed. If there is only one value left, the list element is removed.

x <- list(a = "bla", b = c("ble", "bla"), c = "bli")
while (length(x) > 0) {
  s <- sample(x, size = 1)
  column <- x[[names(s)]]
  value <- sample(unlist(s, use.names = FALSE), size = 1)

  list_element_without_value <- subset(column, column != value)

  x[[names(s)]] <- if (length(list_element_without_value) == 0) {
    NULL
  } else {
    list_element_without_value
  }
}

Upvotes: 1

Dason
Dason

Reputation: 61913

sample(x)

You can't use size=1 on repeated calls and expect it to know not to grab values previously selected. You have to grab all the values you want at one time. This code will shuffle your data and then you can grab the first element when you need it. Then the next time you need something grab the second... And so on.

Upvotes: 0

Related Questions