How to create a matrix in R by filling the data with predefined values in loop?


If we know the total number of rows we want in our matrix and the number of columns then we can use matrix function to create a matrix by filling the data with predefined values. These values must be equal to the multiplication of number of rows and columns.

Check out the below given examples to understand how it works.

Example 1

Following snippet creates a matrix in R by filling the data with predefined values in loop −

n=20
k=2
data=rpois(n*k,5)
M1=matrix(data,nrow=n,ncol=k)
M1

If you execute the above given snippet, it generates the following output −

     [,1] [,2]
[1,]  10   7
[2,]   4   8
[3,]   2   6
[4,]   3   3
[5,]   9   7
[6,]   7   4
[7,]  10   4
[8,]   4   5
[9,]   5   3
[10,]  7   2
[11,]  1   4
[12,]  1   4
[13,]  6   2
[14,]  8   3
[15,]  4   3
[16,]  7   6
[17,]  7   4
[18,] 11   8
[19,]  5   4
[20,]  6   5

Example 2

Following snippet creates a matrix in R by filling the data with predefined values in loop −

nrow=20
col=2
data=round(rnorm(nrow*col),2)
M2=matrix(data,nrow=nrow,ncol=col)
M2

If you execute the above given snippet, it generates the following output −

       [,1]   [,2]
[1,]   1.24  -0.58
[2,]   0.14   0.41
[3,]   1.71  -0.81
[4,]  -0.43   0.09
[5,]  -1.04   0.75
[6,]   0.54  -0.65
[7,]  -0.67   0.66
[8,]   0.64   0.55
[9,]  -1.72  -0.81
[10,] -1.74  -1.00
[11,]  0.69   0.98
[12,]  0.33  -0.17
[13,]  0.87   0.72
[14,] -2.02  -0.84
[15,]  1.21   1.28
[16,]  1.20  -1.34
[17,]  1.03   0.77
[18,]  0.79   0.46
[19,]  2.11   0.27
[20,] -1.45   0.67

Updated on: 22-Nov-2021

587 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements