Home » How to Create a Vector with Random Numbers in R

How to Create a Vector with Random Numbers in R

by Erma Khan

You can use one of the following methods to create a vector with random numbers in R:

Method 1: Create Vector with Random Values in Range

#create vector of 10 random values between 1 and 20
runif(n=10, min=1, max=20)

Method 2: Create Vector with Random Integers in Range

#create vector of 10 random integers between 1 and 20
round(runif(n=10, min=1, max=20), 0)

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

Method 1: Create Vector with Random Values in Range

The following code shows how to create a vector of 10 random values between 1 and 20:

#make this example reproducible
set.seed(1)

#create vector with 10 random numbers between 1 and 20
random_vec 10, min=1, max=20)

#view vector
random_vec

 [1]  6.044665  8.070354 11.884214 18.255948  4.831957 18.069404 18.948830
 [8] 13.555158 12.953167  2.173939

Note that set.seed() ensures that we will get the same random numbers each time.

If we remove set.seed(), the random numbers will be different each time we run the code.

Method 2: Create Vector with Random Integers in Range

The following code shows how to create a vector of 10 random integers between 1 and 50:

#make this example reproducible
set.seed(1)

#create vector with 10 random numbers between 1 and 50
random_vec 10, min=1, max=50), 0)

#view vector
random_vec

 [1] 14 19 29 46 11 45 47 33 32  4

Note that the round() function simply rounds the values created by the runif() function to the nearest whole number.

Also note that the runif() function generates random numbers, including the min and max values.

For example, it’s possible that the vector above could have included both 1 and 50.

Also note that it’s possible for the same number to appear multiple times in the vector when using this method.

Additional Resources

The following tutorials explain how to perform other common tasks in R:

How to Create an Empty Vector in R
How to Remove NA Values from Vector in R
How to Convert Matrix to Vector in R

Related Posts