How to get a range of indices of items in a list in R
Overview
The items of a list can be accessed using their index numbers. In R, the first character of a string, list, or vector has its index value or position as 1. For example, the first character “H” of the string “Hello” has the index value 1, the second character “e” has index value 2, and so on.
Accessing the items of a list
To access the list items as earlier stated, we specify their index value or position in the list.
Example
mylist <- list("orange", "pear", "cashew")# accessing the first item/index 1 of the listmylist[1]
Explanation
We can see from the code above that we can access the first item ("orange") of the list by simply specifying its index value 1.
Getting the range of indices of items
We use the : operator to specify a range of items’ indices of a list, where to start, and where to end.
In the code below, we want to return the list items, starting from the second item to the fourth item.
Example
# creating a listmylist <- list("mango", "orange", "pear", "apple", "lemon", "cashew")# specifying from range 2 to 4(mylist)[2:4]
Explanation
In the code above, we create a list mylist with 5 items using the list() function. We used the : operator to return a range of list indices from index 2 to index 4.