How to create matrix with random integer values in R?

R ProgrammingServer Side ProgrammingProgramming

To create a vector of random integers we can use the function sample.int and if we want to create the matrix of such integers then matrix function will be used along with it. For example, if we want to create a matrix with random integers between 1 to 100 of size 20 with 4 columns and 5 rows then it can be done by using the below command −

matrix(sample.int(100,size=20),nrow=5,ncol=4)

Example1

Live Demo

> M1<-matrix(sample.int(100,size=80,replace=TRUE),nrow=20,ncol=4)
> M1

Output

[,1] [,2] [,3] [,4]
[1,] 61 8 68 81
[2,] 34 33 40 70
[3,] 76 29 51 41
[4,] 31 77 8 94
[5,] 35 57 50 29
[6,] 96 28 83 3
[7,] 11 68 71 81
[8,] 63 50 94 85
[9,] 21 53 99 94
[10,] 31 67 23 62
[11,] 56 47 68 66
[12,] 56 5 77 27
[13,] 59 95 88 64
[14,] 21 1 86 55
[15,] 8 3 72 17
[16,] 29 41 61 99
[17,] 7 62 48 56
[18,] 80 78 97 57
[19,] 26 96 34 19
[20,] 73 88 57 72

Example2

Live Demo

> M2<-matrix(sample.int(1000,size=100,replace=TRUE),nrow=20,ncol=5)
> M2

Output

[,1] [,2] [,3] [,4] [,5]
[1,] 956 707 421 995 589
[2,] 525 300 595 548 109
[3,] 610 216 754 888 864
[4,] 744 240 997 246 371
[5,] 848 535 477 127 938
[6,] 836 648 241 597 608
[7,] 675 629 517 758 469
[8,] 238 433 296 249 776
[9,] 226 552 933 917 625
[10,] 111 584 643 699 573
[11,] 168 239 409 844 850
[12,] 587 387 587 899 672
[13,] 55 612 315 572 574
[14,] 765 646 925 848 584
[15,] 158 191 235 435 19
[16,] 68 631 493 604 65
[17,] 740 976 498 755 534
[18,] 241 548 921 265 343
[19,] 907 364 318 502 141
[20,] 150 739 614 444 189

Example3

Live Demo

> M3<-matrix(sample.int(5000,size=40,replace=TRUE),nrow=20,ncol=2)
> M3

Output

[,1] [,2]
[1,] 2025 4158
[2,] 1372 4495
[3,] 2208 2306
[4,] 1091 476
[5,] 2635 4873
[6,] 1724 3327
[7,] 580 4051
[8,] 546 3927
[9,] 4115 2399
[10,] 1520 4577
[11,] 420 2441
[12,] 2251 1323
[13,] 2908 1415
[14,] 733 3886
[15,] 3556 844
[16,] 2181 2161
[17,] 2771 2349
[18,] 4805 2057
[19,] 2269 4561
[20,] 3110 1250

Example4

Live Demo

> M4<-matrix(sample.int(10,size=100,replace=TRUE),nrow=20,ncol=5)
> M4

Output

[,1] [,2] [,3] [,4] [,5]
[1,] 10 7 6 8 4
[2,] 2 3 9 7 6
[3,] 1 6 10 3 9
[4,] 8 1 8 7 3
[5,] 10 6 10 8 3
[6,] 2 3 9 7 10
[7,] 5 9 2 1 5
[8,] 6 4 10 1 7
[9,] 3 5 2 5 5
[10,] 2 9 8 8 7
[11,] 6 5 8 3 9
[12,] 4 1 9 6 7
[13,] 2 10 9 4 5
[14,] 10 5 2 1 2
[15,] 3 10 9 2 10
[16,] 3 6 8 8 7
[17,] 3 2 9 3 4
[18,] 9 3 3 5 4
[19,] 6 3 1 3 2
[20,] 3 7 1 7 5
raja
Published on 04-Mar-2021 13:23:04
Advertisements