What is which() in R?
Overview
The which() function is used to get the position of the specified argument value in a logical vector. It takes a logical vector as an argument. Otherwise, it throws an error.
Syntax
which(x, arr.ind = FALSE, useNames = TRUE)
Parameters
It takes the following argument values.
x: This is the input logical vector.arr.ind: Ifxis an array,arr.indwill return indexes of the array. Its default value isFALSE.useNames: This is the dimension name/s of an array. Its default value isTRUE.
Return value
It returns the indexes of specified values in the logical vector.
Example
Let's use the which() function to elaborate on its different use cases. It helps in filtering and manipulating the data.
Note: The
cat()method in R is used to print to the screen or in a file.
# Program to show how to use which() function in program# Check position of ASCII characterscat("Using which() to get the position of letters of the English alphabet\n")which(letters== "e")which(letters== "d")which(letters== "u")which(letters== "c")which(letters== "a")which(letters== "t")which(letters== "i")which(letters== "v")which(letters== "e")# Creating a vector of random valuesdata <- c(1, 2, 3, 4, 6, 10, 8, 7, 5, 10)cat("Using which to get index of number 10\n")which(data == 10)cat("Get indexes of numbers less than 8\n")which(data < 8)
Explanation
- Line 4–12: In each line,
which()takes a letter of the English alphabet as an argument and shows its position in the alphabet (1–26) on the console. - Line 14: We create a vector
dataof length 10. - Line 16: The
which(data == 10)statement prints indexes of10in the vector. - Line 18: The
which(data < 8statement prints all indexes where the vector values are less than 8.