# Which Function in R – which()

Which function in R, returns the indices of the logical object when it is TRUE. In other words, which() function in R returns the position of value when it satisfies the specified condition.

#### Syntax of which function in R:

which(x, arr.ind = FALSE)
• x – logical vector
• ind- logical; should array indices be returned when xis an array?

#### Example of Which function in R:

```# which function in R

which(letters=="z")
which(letters=="s")
```

Returns the position of “Z” and “S” in the letters object.so the output will be

 26

 19

#### R Which function for Vector:

```# which function in R for vector

x <- c(1,3,5,7,8)
which(x==3)
which(x>=7)
```

Returns the index position of x=3 and X>=7 in the vector and .so the output will be

 2

 4   5

#### Which function in R for data frame:

Let’s consider default women table.

 height weight 1 58 115 2 59 117 3 60 120 4 61 123 5 62 126 6 63 129 7 64 132 8 65 135 9 66 139 10 67 142 11 68 146 12 69 150 13 70 154 14 71 159 15 72 164

now lets see how to use which() function for data frame in R

```# which function in R for a data frame

which(women\$height==66,arr.ind = FALSE)
which(women\$height>=70,arr.ind = FALSE)
```

output:

 9

 13 14 15

#### Which() function in R for matrix:

First lets generate the matrix

```# matrix creation

m = matrix(rep(c(-1, 0, 1), 4), nrow = 4)
```

the resultant matrix will be

[,1] [,2] [,3]

[1,]   -1    0    1

[2,]    0    1   -1

[3,]    1   -1    0

[4,]   -1    0    1

```# which function in R for matrix

which(m==0,arr.ind=TRUE)
```

It will return array index of the matrix when m==0 so the output will be

row col

[1,]   2   1

[2,]   1   2

[3,]   4   2

[4,]   3   3