Home > Software design >  Random Sample in R: Limiting Number of Repetitionsout of a 2 digit vector
Random Sample in R: Limiting Number of Repetitionsout of a 2 digit vector

Time:03-22

I have the following vector in R: c(0,1).

I am wishing to randomly sample from this vector 10 elements at a time, but such that no more than 2 elements repeat.

The code I have tried is sample(c(0,1),10,replace=T)

But I would like to get

sample(c(0,1),10,replace=T) = (0,1,1,0,1,1,0,0,1,0)

sample(z,4,replace=T) = (0,1,0,1,0,0,1,0,1,0)

but not

sample(z,4,replace=T) = (1,0,0,0,1,1,0,0,0)

And so on.

How could I accomplish this?

CodePudding user response:

Since the number of repeats can only be 1 or 2, and since the value needs to alternate, you can achieve this in a one-liner by randomly choosing 1 or 2 repeats of each of a sequence of 1s and 0s, and truncating the result to 10 elements.

rep(rep(0:1, 5), times = sample(c(1:2), 10, TRUE))[1:10]
#> [1] 0 0 1 1 0 1 1 0 1 0

If you wish to remove the constraint of the sequence always starting with a zero, you can randomly subtract the result from 1:

abs(sample(0:1, 1) - rep(rep(0:1, 5), times = sample(c(1:2), 10, TRUE))[1:10])
#> [1] 1 1 0 0 1 0 0 1 1 0

CodePudding user response:

foo <- function(){
  innerfunc <- function(){sample(c(0, 1), 10, T)}
  x <- innerfunc()
  while(max(rle(x)$lengths) > 2){
    x <- innerfunc()
  }
  x
}

foo()

This function will look at the max length of a sequence of zeroes and ones. If this is > 2, it reruns your sample function, named innerfunc in here.

CodePudding user response:

I think this is an interesting coding practice if you would like to use recurssions, and below might be an option that gives some hints

f <- function(n) {
    if (n <= 2) {
        return(sample(c(0, 1), n, replace = TRUE))
    }
    m <- sample(c(1, 2), 1)
    v <- Recall(n - m)
    c(v, rep((tail(v, 1)   1) %% 2, m))
}
  • Related