How do you create a matrix with random numbers in R?

In R, you can use the runif() function to generate a matrix with random numbers. The runif() function takes three arguments: the minimum value, the maximum value, and the size of the matrix to generate. You can also use the matrix() function to create a matrix with the random values generated by the runif() function. To create a matrix with random numbers in R, you can combine the runif() and matrix() functions.


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

Method 1: Create Matrix with Random Values in Range

#create matrix of 10 random values between 1 and 20
random_matrix <- matrix(runif(n=10, min=1, max=20), nrow=5)

Method 2: Create Matrix with Random Integers in Range

#create matrix of 10 random integers between 1 and 20
random_matrix <- matrix(round(runif(n=10, min=1, max=20), 0), nrow=5)

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

Method 1: Create Matrix with Random Values in Range

The following code shows how to create a matrix with 5 rows consisting of 10 random values between 1 and 20:

#make this example reproducible
set.seed(1)

#create matrix with 10 random numbers between 1 and 20
random_matrix <- matrix(runif(n=10, min=1, max=20), nrow=5)

#view matrix
random_matrix

          [,1]      [,2]
[1,]  6.044665 18.069404
[2,]  8.070354 18.948830
[3,] 11.884214 13.555158
[4,] 18.255948 12.953167
[5,]  4.831957  2.173939

The result is a matrix with 5 rows and 2 columns, where each value in the matrix is between 1 and 20.

Method 2: Create Matrix with Random Integers in Range

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

#make this example reproducible
set.seed(1)

#create matrix with 10 random integers between 1 and 50
random_matrix <- matrix(round(runif(n=10, min=1, max=50), 0), nrow=5)

#view matrix
random_matrix

     [,1] [,2]
[1,]   14   45
[2,]   19   47
[3,]   29   33
[4,]   46   32
[5,]   11    4

The result is a matrix with 5 rows and 2 columns, where each value in the matrix is an integer between 1 and 50.

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

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

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

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

x