How to sample for 3 different variables to result a unique variable out of the 3 every time?

Viewed 25

working on a project and i can't figure out how to get unique values every time. The program works but I don't know how to filter unique values so that the 3 strings are different any time. Such as a=abc, b=xyz, c=lmn every time some variation of those, but all unique values.

a = c('ABC', 'XYZ', 'LMN')
if(length(a)==3){
  b = sample(a, size = 1, replace = TRUE)
  c = sample(a[!(c %in% d)], size = 1, replace = TRUE)
  a = sample(a[!(a %in% c(c, b))], size = 1, replace = TRUE)
  }
2 Answers

In cases where the number of items selected equals the number of possible items you are getting a particular kind of sample called a permutation. The sample function is set up to do that:

> a = c('ABC', 'XYZ', 'LMN')
> sample(a,3)
[1] "ABC" "XYZ" "LMN"
> sample(a,3)
[1] "ABC" "XYZ" "LMN"
> sample(a,3)
[1] "ABC" "LMN" "XYZ"
> sample(a,3)
[1] "XYZ" "LMN" "ABC"
> sample(a,3)
[1] "LMN" "ABC" "XYZ"

If the number of items to be selected is less than the size of the "universe", then you can still use sample because the default for the "replacement" argument is FALSE.

> a = c('ABC', 'XYZ', 'LMN', "jrw", "wxz")
> sample(a,3)
[1] "XYZ" "LMN" "wxz"
> sample(a,3)
[1] "LMN" "jrw" "ABC"
> sample(a,3)
[1] "wxz" "XYZ" "ABC"
> sample(a,3)
[1] "ABC" "wxz" "jrw"

I got the sense that 'sample' was some part of a given sequence, potentially A in ABC. But still going with expanding universe

set.seed(42)
a3 <- unlist(strsplit(a, split=NULL))
> a3
[1] "A" "B" "C" "X" "Y" "Z" "L" "M" "N"
b <- sample(a3, size = 3, replace = FALSE)
b
[1] "A" "Y" "N"
setdiff(a3,b)
[1] "B" "C" "X" "Z" "L" "M"
c <- setdiff(a3,b)
d <- sample(c, size = 3, replace = FALSE)
d
[1] "B" "C" "Z"
e <- setdiff(c, d)
e
[1] "X" "L" "M"

But I could have misinterpreted the goal. In a pinch:

a[sample(order(a), size = 3)]
[1] "LMN" "XYZ" "ABC"
# or
 combn(sample(a,size=3), 3, paste, sep  = ',')
     [,1] 
[1,] "XYZ"
[2,] "LMN"
[3,] "ABC"

you harvest three results at a time and assign them to a,b,c; then pick again.

Related