How to find the row and column index of a character value in an R data frame?

R ProgrammingServer Side ProgrammingProgramming

To find the row and column index for a numerical value in an R data frame we use which function and if the value is character then the same function will be used but we need to pass the value appropriately. For example, if we have a data frame called df that contains a value say Data then we can find the row and column index of Data by using the command as which(df=="Data",arr.ind=TRUE).

Example1

Consider the below data frame −

Live Demo

> x1<-sample(c("Male","Female"),20,replace=TRUE)
> x2<-rpois(20,5)
> df1<-data.frame(x1,x2)
> df1

Output

    x1    x2
1 Female  5
2 Female  5
3 Female  6
4 Female  6
5   Male  6
6 Female  6
7 Female  7
8   Male  0
9   Male  4
10  Male  3
11  Male  8
12 Female 6
13 Female 5
14  Male  5
15  Male  4
16  Male  7
17 Female 4
18  Male  4
19  Male  3
20  Male  5

Finding the row and column index of Male in df1 −

> which(df1=="Male",arr.ind=TRUE)

Output

     row col
[1,]  5   1
[2,]  8   1
[3,]  9   1
[4,]  10  1
[5,]  11  1
[6,]  14  1
[7,]  15  1
[8,]  16  1
[9,]  18  1
[10,] 19  1
[11,] 20  1

Example2

Live Demo

> y1<-sample(c("India","UK","USA"),20,replace=TRUE)
> y2<-sample(c("Egypt","UK","Sudan"),20,replace=TRUE)
> df2<-data.frame(y1,y2)
> df2

Output

   y1     y2
1  UK    Sudan
2  USA   Egypt
3  India UK
4  UK    Egypt
5  UK    Sudan
6  India UK
7  USA   Egypt
8  UK    UK
9  UK    Sudan
10 USA   Egypt
11 UK    Egypt
12 India Egypt
13 India Egypt
14 India Egypt
15 UK    UK
16 India Sudan
17 UK    Sudan
18 UK    UK
19 UK    Sudan
20 India Sudan

Finding the row and column index of UK in df2 −

> which(df2=="UK",arr.ind=TRUE)

Output

     row col
[1,]  1   1
[2,]  4   1
[3,]  5   1
[4,]  8   1
[5,]  9   1
[6,]  11  1
[7,]  15  1
[8,]  17  1
[9,]  18  1
[10,] 19  1
[11,] 3   2
[12,] 6   2
[13,] 8   2
[14,] 15  2
[15,] 18  2

Example3

Live Demo

> z1<-sample(c("Milk","Curd","Pastry"),20,replace=TRUE)
> z2<-sample(c("Milk","Tea"),20,replace=TRUE)
> df3<-data.frame(z1,z2)
> df3

Output

    z1    z2
1 Pastry  Tea
2 Pastry  Milk
3 Milk    Milk
4 Pastry  Tea
5 Curd    Tea
6 Pastry  Tea
7 Curd    Tea
8 Curd    Tea
9 Milk    Tea
10 Milk   Tea
11 Pastry Milk
12 Pastry Tea
13 Curd   Milk
14 Milk   Tea
15 Milk   Milk
16 Curd   Tea
17 Milk   Tea
18 Curd   Tea
19 Curd   Milk
20 Milk   Milk

Finding the row and column index of Milk in df3 −

> which(df3=="Milk",arr.ind=TRUE)

Output

     row col
[1,]  3   1
[2,]  9   1
[3,]  10  1
[4,]  14  1
[5,]  15  1
[6,]  17  1
[7,]  20  1
[8,]  2   2
[9,]  3   2
[10,] 11  2
[11,] 13  2
[12,] 15  2
[13,] 19  2
[14,] 20  2
raja
Published on 04-Mar-2021 08:37:32
Advertisements