![]() |
In this article, we will examine various methods to randomize rows of a matrix in the R Programming Language. What is a matrix?A matrix is a two-dimensional arrangement of data in rows and columns. A matrix can able to contain data of various types such as numeric, characters, and logical values. Inside the matrix, rows are arranged horizontally and columns are arranged vertically. It is possible to access the data in the matrix easily. By using the function ‘matrix()’ matrices are created. How to randomize the rows in a matrixR language offers various methods to randomize rows in a matrix. By using these methods provided by R, it is possible to randomize the rows easily. Some of the methods to randomize rows in the matrix are: By using the sample() FunctionThese method is used to randomize the rows in a matrix efficiently. The syntax is: sample(matrix)
In the below example, we created a matrix and randomized the rows in the matrix using ‘sample()’.
Output: [1] "Original matrix:" In the below example, we created a matrix and randomized the rows in the matrix using ‘sample()’.
Output: [1] "Original matrix is" By using the sample.int() FunctionThese method is used to randomize the rows in a matrix efficiently. The syntax is: sample.int(matrix)
In the below example, we created a matrix and randomized the rows in the matrix using ‘sample.int()’.
Output:[1] "Original matrix is"
[,1] [,2] [,3] [,4]
[1,] 21 26 31 36
[2,] 22 27 32 37
[3,] 23 28 33 38
[4,] 24 29 34 39
[5,] 25 30 35 40
[1] "Randomized rows in the matrix is"
[,1] [,2] [,3] [,4]
[1,] 24 29 34 39
[2,] 21 26 31 36
[3,] 25 30 35 40
[4,] 22 27 32 37
[5,] 23 28 33 38
In the below example, we created a matrix and randomized the rows in the matrix using ‘sample.int()’.
Output: [1] "Original matrix is"
[,1] [,2] [,3] [,4] [,5]
[1,] "a" "f" "k" "p" "u"
[2,] "b" "g" "l" "q" "v"
[3,] "c" "h" "m" "r" "w"
[4,] "d" "i" "n" "s" "x"
[5,] "e" "j" "o" "t" "y"
[1] "Randomised rows in the matrix is"
[,1] [,2] [,3] [,4] [,5]
[1,] "d" "i" "n" "s" "x"
[2,] "e" "j" "o" "t" "y"
[3,] "c" "h" "m" "r" "w"
[4,] "a" "f" "k" "p" "u"
[5,] "b" "g" "l" "q" "v" ConclusionIn conclusion, we learned about how to randomize the rows in a matrix by using various methods . R language provides versatile tools while dealing with these matrices. |
Reffered: https://www.geeksforgeeks.org
R Language |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |