VOOZH about

URL: https://www.geeksforgeeks.org/r-language/which-function-in-r/

⇱ which() Function in R - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

which() Function in R

Last Updated : 23 Aug, 2021

which() function in R Programming Language is used to return the position of the specified values in the logical vector.

Syntax: which(x, arr.ind, useNames)

Parameters: This function accepts some parameters which are illustrated below:

  • X: This is the specified input logical vector
  • Arr.ind: This parameter returns the array indices if x is an array.
  • useNames: This parameter says the dimension names of an array.

Return value: This function returns the position of the specified values in the logical vector.

Example 1: Which() function applying to the alphabet

In the below example, which() function returns the alphabetical position of the specified letter. For example, a is the first letter in the alphabet sequence that's why 1 is returned and z is the last letter in the sequence so 26 is returned.

Output :

[1] 1
[1] 4
[1] 26
[1] 16
[1] 7

Example 2:  which() function with vectors

In the below example, the position of some elements of the specified vector is being returned which the help of which() function.

Output:

[1] 5
[1] 3
[1] 4
[1] 4 5

Example 3: which() function with dataframe

 In the below example, which() function is used to find the columns in a data frame with numeric values.

An Iris data set is used as a data frame that contains 4 columns for numerical values and 1 column for categorical values i.e., Species. The which() function find the columns name from the data set that contain numeric values.

Output:

👁 Image

Example 4: which() function with the matrix

In the below example, which() function is used to find the position of an element in the specified matrix.

Here the position of value 2 in the specified matrix is being calculated.

Output:

👁 Image
Comment
Article Tags:

Explore