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.
R
which ( letters == "a" )
which ( letters == "d" )
which ( letters == "z" )
which ( letters == "p" )
which ( letters == "g" )
|
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.
R
vector <- c (3, 5, 1, 6, 12, 4)
which (vector == 12)
which (vector == 1)
which (vector == 6)
which (vector > 5)
|
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.
R
data_set <- datasets::iris
head (data_set)
Result <- which ( sapply (data_set, is.numeric))
colnames (data_set)[Result]
|
Output:
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.
R
Matrix <- matrix ( rep ( c (1, 2, 3), 4), nrow = 4)
Matrix
which (Matrix == 2, arr.ind = T)
|
Output:
Last Updated :
23 Aug, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...