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.
which(x, arr.ind = FALSE, useNames = TRUE)
It takes the following argument values.
x
: This is the input logical vector.arr.ind
: If x
is an array, arr.ind
will return indexes of the array. Its default value is FALSE
.useNames
: This is the dimension name/s of an array. Its default value is TRUE
.It returns the indexes of specified values in the logical vector.
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)
which()
takes a letter of the English alphabet as an argument and shows its position in the alphabet (1–26) on the console. data
of length 10.which(data == 10)
statement prints indexes of 10
in the vector.which(data < 8
statement prints all indexes where the vector values are less than 8.