How to generate a sample in R or which the distance between the numbers drawn is equal

344 views Asked by At

I am working in R and I am trying to generate a sample of N, but the distance between all the numbers must be equal. So for example a set of 5 numbers out of 1:10 between which the distance of each number is 2 would give (c(1,3,5,7,9).

Right now I have runif(N, min = 0, max = 10), but this will give me just N numbers randomly. The same happens when I use the sample function.

I have been trying to figure this out for the past day but could not find a thread/function with a solution. Does someone have a clue?

1

There are 1 answers

0
CPak On

Try this

myfun <- function(R, N, I) {
              max.start <- tail(range,1)-(N-1)*2 # sequence of output cannot extend beyond range
              start <- sample(max.start, 1)
              seq(start, by=I, length.out=N)
         }

range <- 1:10
N <- 5
interval <- 2

# 1 trial
myfun(range, N, interval)
# [1]  2  4  6  8 10

# 10 trials
t(replicate(10, myfun(range, N, interval)))
      # [,1] [,2] [,3] [,4] [,5]
 # [1,]    1    3    5    7    9
 # [2,]    1    3    5    7    9
 # [3,]    2    4    6    8   10
 # [4,]    1    3    5    7    9
 # [5,]    1    3    5    7    9
 # [6,]    2    4    6    8   10
 # [7,]    2    4    6    8   10
 # [8,]    2    4    6    8   10
 # [9,]    1    3    5    7    9
# [10,]    2    4    6    8   10