Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

r
list
communitycreator

How to access the items of a list in R

Onyejiaku Theophilus Chidalu

Overview

A list in R is simply a collection of ordered or changeable data.

The list items are combined together using the list() function. This function takes the items we want in our list as its parameter.

Now, let’s create a list.

Code example

# Vector of strings
my_list1 <- list("pear", "cherry", "lemon")

# vector of numbers
my_list2 <- c(1, 2, 3, 4, 5)

# Printing the vectors
my_list1
my_list2
Creating a list

Code explanation

  • Line 2: We create a list my_list1 containing string values or items.

  • Line 5: We create another list my_list2 containing numerical values or items.

  • Lines 8-9: We print the two lists we created.

How to access the items of a list

To access the items of a list, we simply refer to its index number inside brackets []. In R, the first list item has its index as 1, the second item has its index as 2, and so on.

In the code below, we want to access the items of a list.

Code example

# creating a list
my_list <- list("pear", "cherry", "lemon")

# accessing the first item of the list
my_list[1]

# accessing the second item of the list
my_list[2]
Accessing the items of a list in R

Code explanation

We can see that we were able to access the items of the vector my_vector by simply referring to the index number of the specific item inside brackets [].

RELATED TAGS

r
list
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring