This function produces an equal number of left and right eyes (coded as left = 0, right = 1) in a random sequence.
The function can be entered into R using the following short piece of code:
equaleyes <- function(x){
prob.vector <- c(rep(1,ceiling(x/2)),rep(0,floor(x/2)))
eye.seq <- sample(prob.vector,x,replace = FALSE)
The code works as follows: x is the number of eyes required. A sequence of 1s followed by a sequence of 0s is placed in prob.vector (for probability vector). The number of 1s is exactly half of the total number of eyes required, rounded up if necessary using “ceiling.” The number of 0s also is exactly half of the total number of eyes, rounded down if necessary using “floor.” This means that for an even number of eyes, there will be an equal number of 1s and 0s, while for an odd number of eyes, there will be an extra “1” in the sequence.
Next, numbers are picked at random from prob.vector and placed in eye.seq (for eye sequence). This is repeated until all of the numbers have been placed in eye.seq. As each number is taken, they are not replaced in the list (replace = FALSE); thus each eye can be picked only once, and equal numbers of left and right eyes appear in the final list, but in a randomized order.
Once the function has been entered, typing equaleyes(x), where x is the number of eyes in the sequence, will generate a random sequence of left and right eyes with equal numbers in each group. As mentioned, where x is an odd number, the total number of right eyes will exceed the total number of left eyes by 1.