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:
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
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.
Statistics Globe Newsletter