Create Random Matrix in R (Example)
In this post, I’ll explain how to fill a matrix with random values in the R programming language.
Table of contents:
Let’s do this!
Example: Create Random Matrix Using sample() Function
In this example, I’ll illustrate how to use the sample function to generate a matrix containing random numbers in R.
For this, we first should set a random seed to make our example reproducible:
set.seed(659235) # Set seed
Next, we can use the matrix and sample functions to draw random numbers and fill them into our matrix:
mat <- matrix(sample(1:100, # Apply matrix & sample functions 20, # Specify number of values replace = TRUE), # Set replace to FALSE or TRUE ncol = 4) # Specify number of columns mat # Print random matrix

As shown in Table 1, the previous R programming syntax has managed to construct a matrix object with five rows and four columns. The data cells of the matrix are filled with randomly drawn values.
Note that we have set the replace argument of the sample function to be equal to TRUE. This means that there is a chance that the same value appears multiple times in our matrix.
Furthermore, we have specified to draw 20 values and that these values should be spread across four columns. Note that the number of values divided by the number of columns needs to be an integer value. Alternatively, we could also specify the number of rows using the nrow argument.
Video, Further Resources & Summary
If you need more info on the contents of the present page, you may watch the following video of my YouTube channel. I’m explaining the R programming code of this article in the video:
In addition, you may want to read some of the related tutorials on my website:
- Convert Character Matrix to Numeric
- Convert Matrix to List of Column-Vectors
- Convert Vector to Matrix
- Return Index Position of Element in Matrix Using which() Function
- R Programming Overview
Summary: In this tutorial you have learned how to draw random numbers and fill them into a matrix in the R programming language. If you have further questions and/or comments, please tell me about it in the comments.
Â
Subscribe to the Statistics Globe Newsletter
Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.
Thank you!
Welcome to the Statistics Globe newsletter. From now on, I’ll send you regular emails about statistics, data science, AI, and programming with R and Python.
I’m Joachim Schork. On this website, I provide statistics tutorials as well as code in Python and R programming.
Statistics Globe Newsletter
Get regular updates on the latest tutorials, offers & news at Statistics Globe. I hate spam & you may opt out anytime: Privacy Policy.
Thank you!
Please check your email inbox and click the confirmation link to complete your subscription. If you don’t see the email within a few minutes, please also check your spam/junk folder.






