How to Fill Matrix with Random Numbers in R (Example Code)
This tutorial explains how to draw random numbers and fill them into a matrix in the R programming language.
Example: Apply sample() Function to Draw Random Values for Matrix
set.seed(984375) # Draw random values for matrix example_matrix <- matrix(sample(1:100, 50, replace = TRUE), nrow = 10) example_matrix # Display random matrix in RStudio console # [,1] [,2] [,3] [,4] [,5] # [1,] 81 96 50 1 70 # [2,] 80 26 43 67 83 # [3,] 29 39 95 79 3 # [4,] 31 65 40 75 54 # [5,] 29 5 90 92 30 # [6,] 13 5 80 72 19 # [7,] 47 5 80 98 22 # [8,] 61 98 71 41 9 # [9,] 22 46 56 7 63 # [10,] 83 9 43 38 93 |
set.seed(984375) # Draw random values for matrix example_matrix <- matrix(sample(1:100, 50, replace = TRUE), nrow = 10) example_matrix # Display random matrix in RStudio console # [,1] [,2] [,3] [,4] [,5] # [1,] 81 96 50 1 70 # [2,] 80 26 43 67 83 # [3,] 29 39 95 79 3 # [4,] 31 65 40 75 54 # [5,] 29 5 90 92 30 # [6,] 13 5 80 72 19 # [7,] 47 5 80 98 22 # [8,] 61 98 71 41 9 # [9,] 22 46 56 7 63 # [10,] 83 9 43 38 93