To get the index of a specified item in a vector in R, you can use the which()
function.
In this example,
num_vec
.which()
function along with equality comparison to find the index of the specified item.index
.num_vec <- c(1, 2, 3, 4, 5)
item <- 3
index <- which(num_vec == item)
print(index)
[1] 3
In this example,
char_vec
.which()
function along with equality comparison to find the index of the specified item.index
.char_vec <- c("apple", "banana", "cherry", "date")
item <- "banana"
index <- which(char_vec == item)
print(index)
[1] 2
In this tutorial, we learned How to get the Index of Specified Item in a Vector in R language with well detailed examples.