-1

I am wondering how to generate random numbers in the following way in R:

 randomly choose 1 number between 1 and 15
 randomly choose 1 number between 16 and 30
 ... 
 randomly choose 1 number between 86 and 100

I know that I can do this with a loop but I am wondering if there is any non-loop way to do this. I tried to google around but didn't find much helpful.

MBorg
  • 1,345
  • 2
  • 19
  • 38
lll
  • 1,049
  • 2
  • 13
  • 39
  • Sure there is. Please provide some form of [reproducible question](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) (also https://stackoverflow.com/help/mcve) and we might be able to help. – r2evans Nov 17 '17 at 04:03

3 Answers3

4

We can write a function using sapply and sample in the following way

select_1_number_in_range <- function(start, stop, interval) {
  sapply(seq(start, stop, interval), function(x) sample(x:(x+interval-1), 1))
}

set.seed(31)
select_1_number_in_range(1, 100, 15)


#[1]   9  31  37  52  76  83 104

We generate a sequence between the range with the interval as by argument and select one number from each list.

Note : 100 is not divisible by 15 so this gets extended till 105.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
4

First off, 100 is not divisible by 15 so this answer will go up to 105 instead.

Start by creating a matrix of integers 1:105 with 105/15 rows. Then we simply sample one column for each row. This way we get a random value from each of our ranges without using a loop.

## set up
n <- 105
m <- matrix(1:n, nrow=n/15, byrow=TRUE)
## execute
m[cbind(1:nrow(m), sample(ncol(m), nrow(m)))]
# [1]   5  23  33  51  74  77 103

Here we can see a run of 10 replications. Each column is one sample.

replicate(10, m[cbind(seq(nrow(m)), sample(ncol(m), nrow(m)))])
#      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
# [1,]    4   11   10    3    8    5   14   11    5    15
# [2,]   20   20   17   23   25   25   24   19   23    19
# [3,]   45   34   42   35   35   42   32   38   39    44
# [4,]   55   54   49   55   54   46   53   60   47    46
# [5,]   67   73   61   62   75   66   67   62   61    69
# [6,]   83   83   78   79   77   89   79   87   87    86
# [7,]   91  102   95  104   96   94   93   95  100    97
Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
0

Use runif(). It works as runif(n, min = x, max = y).

n is the number of randomly generated numbers that you want. min and max are the range from which the numbers can be drawn.

In your case:

> runif(1, min=1, max=15)
[1] 2.916329
> runif(1, min=16, max=30)
[1] 28.54506
> runif(1, min=86, max=100)
[1] 87.43045

Note that the numbers generated above have decimal figures. If you want whole integers, insert the above inside round() i.e.

> round(runif(1, min=1, max=15), digits=0)
[1] 7
> round(runif(1, min=16, max=30), digits=0)
[1] 23
> round(runif(1, min=86, max=100), digits=0)
[1] 90
MBorg
  • 1,345
  • 2
  • 19
  • 38