# How to find the row and column position of a value as vector in an R matrix?

To find the row and column position of a value as vector in an R matrix, we can follow the below steps −

• First of all, create a matrix.
• Then, find the row and column position of a particular value using which function and reading the output with as.vector function.

## Example 1

Create a matrix

Let's create a matrix as shown below −

Live Demo

M1<-matrix(round(rnorm(60),2),ncol=3)
M1

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

      [,1]   [,2] [,3]
[1,]  -0.86 -0.49 0.19
[2,]  -2.42 -2.09 0.06
[3,]  -2.87  0.61 0.74
[4,]  -1.89 0.37 0.86
[5,]  -1.05 -1.22 -0.29
[6,]   0.45 -0.42 -1.31
[7,]   1.73 1.00 -0.37
[8,]   1.61 0.02 0.81
[9,]   1.98 -0.24 -0.20
[10,] -1.55 0.56 0.14
[11,]  1.07 0.07 0.47
[12,]  0.28 0.49 -1.45
[13,]  1.29 -1.46 0.24
[14,] -1.04 -0.70 -1.51
[15,] -1.86 0.04 -0.79
[16,]  0.10 -0.74 0.47
[17,] -0.33 -0.05 -0.66
[18,]  1.74 1.31 0.90
[19,]  0.95 -0.21 0.69
[20,]  0.04 -0.62 -0.02

## Find the row and column position of a value

Using which function to find the row and column position of value 0.19 −

Live Demo

M1<-matrix(round(rnorm(60),2),ncol=3)
as.vector( which(M1==0.19,arr.ind=TRUE))

### Output

[1] 1 3

## Example 2

Create a matrix

Let’s create a matrix as shown below −

Live Demo

M2<-matrix(round(runif(60,2,5),2),ncol=3)
M2
     [,1] [,2] [,3]
[1,] 4.27 4.03 3.52
[2,] 4.57 2.52 2.08
[3,] 3.25 3.98 4.40
[4,] 2.77 3.50 3.94
[5,] 4.53 4.64 4.39
[6,] 3.44 3.83 3.26
[7,] 3.77 2.02 3.56
[8,] 2.12 3.54 3.74
[9,] 3.73 2.19 2.22
[10,] 4.54 3.16 4.11
[11,] 3.51 2.05 3.85
[12,] 4.88 3.93 2.74
[13,] 3.38 2.82 4.77
[14,] 3.63 3.76 2.84
[15,] 3.84 3.81 4.57
[16,] 3.18 2.76 4.44
[17,] 4.19 4.73 4.20
[18,] 3.55 4.99 2.56
[19,] 4.79 3.14 2.30
[20,] 4.96 2.99 3.54

## Find the row and column position of a value

Using which function to find the row and column position of value 2.05 −

Live Demo

M2<-matrix(round(runif(60,2,5),2),ncol=3)
as.vector(which(M2==2.05,arr.ind=TRUE))

### Output

[1] 11 2

Updated on: 14-Aug-2021

588 Views