How to grab any desired row or a column in a matrix in R?Explain with an example

623    Asked by MatthewTAYLOR in Data Science , Asked on Nov 18, 2019
Answered by Matthew TAYLOR

To grab a row or a column, we have to define a matrix.A matrix is usually an array of numbers or a mathematical object defined in a rectangular shape. We can pass in different conditions to perform when we define a matrix.

mat=<- matrix(1:50,byrow=TRUE,nrow=5)

The matrix will contain 5 rows and 5 columns as follows

mat

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]

[1,] 1 2 3 4 5 6 7 8 9 10

[2,] 11 12 13 14 15 16 17 18 19 20

[3,] 21 22 23 24 25 26 27 28 29 30

[4,] 31 32 33 34 35 36 37 38 39 40

[5,] 41 42 43 44 45 46 47 48 49 50

To grab the first row, we can do the following

mat[1,]

[1] 1 2 3 4 5 6 7 8 9 10

To grab the first column, we can do the following

mat[,1]

[1] 1 11 21 31 41



Your Answer

Interviews

Parent Categories