How to randomly draw an element without having duplicates values in a loop

Viewed 35

UPDATED QUESTION :

In a loop, I would like to choose a color for each occurrence without ever having the same twice

myvec <- c("green","blue","red","orange","dark","white")

for (i in (1:6)) {
    
    mycolor <- sample(myvec,1,replace=F)
    
    print(mycolor)
    
}

# Return
[1] "dark"
[1] "blue"
[1] "red"
[1] "red"
[1] "blue"
[1] "blue"
4 Answers

This works for me:

myvec <- c("green","blue","red","orange","dark","white")

for (i in (1:6)) {
    
    mycolor <- sample(myvec,1,replace=F)
    
    print(mycolor)
    myvec <- setdiff(myvec, mycolor)
    
}

From @Limey's comment: Take the sample before the loop:

myvec <- c("green","blue","red","orange","dark","white")

mycolor <- sample(myvec, replace=F)

for (i in (1:6)) {    
  print(mycolor[i])
}

You can scramble your color vector, so you can just use the colors in the scrambled order, later:

myvec <- c("green","blue","red","orange","dark","white")
scram <- rnorm(length(myvec),0,1)
myvec = myvec[order(scram)] ## Now, it's randomly sorted

for (i in (1:6)) {
    mycolor <- myvec[i]
    print(mycolor)  
}

What about a while loop?

myvec <- c("green","blue","red","orange","dark","white")
my_colors = c()
while (length(my_colors) < 6) {
        
        mycolor <- sample(myvec,1,replace=F)
        
        if (!mycolor %in% my_colors) {
                my_colors = c(my_colors, mycolor)
                print(mycolor)
        } else {
                next
        }
        
}

Output:

[1] "blue"
[1] "white"
[1] "orange"
[1] "green"
[1] "red"
[1] "dark"

my_colors will contain your colors:

my_colors

[1] "blue"   "dark"   "green"  "white"  "red"    "orange"
Related