How to Generate Random Numbers in R (With Examples)

You can use the following methods to generate random numbers in R:

Method 1: Generate One Random Number in Range

```#generate one random number between 1 and 20
runif(n=1, min=1, max=20)
```

Method 2: Generate Multiple Random Numbers in Range

```#generate five random numbers between 1 and 20
runif(n=5, min=1, max=20)```

Method 3: Generate One Random Integer in Range

```#generate one random integer between 1 and 20
sample(1:20, 1)
```

Method 4: Generate Multiple Random Integers in Range

```#generate five random integers between 1 and 20 (sample with replacement)
sample(1:20, 5, replace=TRUE)

#generate five random integers between 1 and 20 (sample without replacement)
sample(1:20, 5, replace=FALSE)
```

The following examples show how to use each of these methods in practice.

Method 1: Generate One Random Number in Range

The following code shows how to generate one random number between 1 and 20:

```#generate one random number between 1 and 20
runif(n=1, min=1, max=20)

[1] 8.651919
```

This function generates 8.651919 as the random number between 1 and 20.

Method 2: Generate Multiple Random Numbers in Range

The following code shows how to generate five random numbers between 1 and 20:

```#generate five random numbers between 1 and 20
runif(n=5, min=1, max=20)

[1] 12.507360  6.719675  1.836038 17.685829 16.874723
```

This function generates five random numbers between 1 and 20.

Method 3: Generate One Random Integer in Range

The following code shows how to generate one random integer between 1 and 20:

```#generate one random integer between 1 and 20
sample(1:20, 1)

[1] 7
```

This function generates 7 as the random integer between 1 and 20.

Method 4: Generate Multiple Random Integers in Range

The following code shows how to generate five random integers between 1 and 20:

```#generate five random integers between 1 and 20 (sample with replacement)
sample(1:20, 5, replace=TRUE)

[1] 20 13 15 20  5

#generate five random integers between 1 and 20 (sample without replacement)
sample(0:20, 5, replace=FALSE)

[1] 6 15 5 16 19
```

Note that if we use replace=TRUE then we allow the same integer to be generated more than once.

However, if we use replace=FALSE then we do not allow the same integer to be generated more than once.