How to find the index of values in matrix column in R if they occur once?



To find the index of values in R matrix column if they occur once, we can follow the below steps −

  • First of all, create a matrix.

  • Then, use which function along with duplicated function and single square brackets for subsetting to find the index of values in a column if they occur once.

Example 1

Create the data frame

Let’s create a data frame as shown below −

M1<-matrix(rpois(25,10),ncol=1)
M1

Output

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

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

Find the index of values in a column if they occur once

Using which function along with duplicated function and single square brackets for subsetting to find the index of values in the column of matrix M1 if they occur once −

M1<-matrix(rpois(25,10),ncol=1)
which(!(M1[] %in% M1[][duplicated(M1[])]))

Output

[1] 9 20 21

Example 2

Create the data frame

Let’s create a data frame as shown below −

M2<-matrix(round(rnorm(25),1),ncol=1)
M2

Output

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

     [,1]
[1,]   1.7
[2,]  -1.0
[3,]  -1.1
[4,]   0.8
[5,]   0.7
[6,]   0.7
[7,]   1.9
[8,]  -1.6
[9,]   2.7
[10,]  0.9
[11,] -0.6
[12,]  1.0
[13,] -2.1
[14,] -1.1
[15,]  1.4
[16,]  0.2
[17,] -0.7
[18,]  1.4
[19,]  0.6
[20,] -0.6
[21,]  0.0
[22,] -0.1
[23,]  0.6
[24,]  0.5
[25,] -0.9

Find the index of values in a column if they occur once

Using which function along with duplicated function and single square brackets for sub setting to find the index of values in the column of matrix M2 if they occur once −

M2<-matrix(round(rnorm(25),1),ncol=1)
which(!(M2[] %in% M2[][duplicated(M2[])]))

Output

[1] 2 3 6 7 10 12 14 16 17 18 19 21 23

Advertisements