Search code examples
rrandomsample

sample sequence of successive integer of an interval


I have a question about sampling: I would like to sample successive number in a vector without replacement. Is there a simple way to do so? For example,

sample(c(1:100), 10, replace = F)
76 99 94 53 12 34  5 82 75 30

gives me 10 number between 1 and 100. Now I would like to have 10 sequence of 3 successive integer without replacement: c(2,3,4), c(10,11,12), c(82,83,84) etc.

The different sequences can't overlap, that is if c(2,3,4) is my first sampling, then none of the following one can have these numbers.

I would even look for the possibility of sampling 10 sequences of different sizes, the sizes given by a vector like

sizevec <- sample(c(1:4),10,replace = T)

Thanks for the help


Solution

  • A solution using tow while loop to take samples. After running the code, x is a list of desired output.

    # Set seed for reproduciblility
    set.seed(123)
    
    # Create a list to store values
    x <- list()
    # Create a vector to store values in x
    y <- integer()
    
    # Set the threshold to stop
    threshold <- 4
    
    # Set the condition
    condition <- TRUE
    
    while (length(x) < threshold){
      while (condition){
        # Sample a number between 1 to 98
        s <- sample(c(1:98), 1)
        # Create a sequence
        se <- s:(s + 2)
        # Check if the values in se is in y, save it to the condition
        condition <- any(se %in% y) 
      }
      # Save se to the list
      x[[length(x) + 1]] <- se
      # Update y
      y <- unlist(x)
      # Reset the condition 
      condition <- TRUE
    }
    
    # View the results
    x
    # [[1]]
    # [1] 29 30 31
    # 
    # [[2]]
    # [1] 79 80 81
    # 
    # [[3]]
    # [1] 41 42 43
    # 
    # [[4]]
    # [1] 89 90 91