Return True Indices of a Logical Object in R Programming – which() Function

which() function in R Language is used to return the indices of the object which return true for the logical operation passed as argument.

Syntax: which(x, arr.ind)

Parameters:
x: logical object
arr.ind: Boolean value to display indices

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# R program to illustrate 
# the use of which() function
  
# Create a matrix
x <- matrix(1:9, 3, 3)
x
  
# Calling which() function
which(x %% 2 == 0, arr.ind = TRUE)

chevron_right


Output:



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

Here, in the above code, the which() function returns the indices of all the even numbers present in the matrix.

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# R program to illustrate 
# the use of which() function
  
# Using predefined dataset
BOD
  
# Calling which() function
which(BOD$demand == 19, arr.ind = TRUE)

chevron_right


Output:

  Time demand
1    1    8.3
2    2   10.3
3    3   19.0
4    4   16.0
5    5   15.6
6    7   19.8
[1] 3
My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.