To find the index of a specified element in a list in R, you can use the which
function.
In this example,
my_list
with some elements.which
function to find the index of a specific element. The function returns the positions of elements that are TRUE for the given condition.which
function returns the index of the first occurrence of the element in the list, or an integer(0) if the element is not found.my_list <- c(10, 20, 30, 40, 50)
index <- which(my_list == 40)
cat('Index of element is:', index)
Index of element is: 4
In this example,
my_list
with some string elements.which
function to find the index of a specific string. The function returns the positions of elements that are TRUE for the given condition.which
function returns the index of the first occurrence of the string in the list, or an integer(0) if the string is not found.my_list <- c('apple', 'banana', 'cherry', 'date', 'elderberry')
index <- which(my_list == 'cherry')
cat('Index of element is:', index)
Index of element is: 3
In this tutorial, we learned How to get the Index of Specified Element in a List in R language with well detailed examples.