How to join two or more lists in R

Overview

A list in R is a collection of ordered and changeable data of the same type. A list contains different data types, such as strings or numbers.

The elements contained in a given list are referred to as items.

Creating a list

We use the list() function to create a list in R. Its parameter values are the items you want in the list.

Example

# creating a string and numerical lists
mylist1 <- list("cherry", 'banana', 'orange')
mylist2 <- list(1, 2, 3, 4, 5)
# to print the lists
mylist1
mylist2

Explanation

We create two list variables, mylist1 and mylist2. They contain strings and numbers, respectively.

Joining two lists

To join or concatenate two different lists in R, we use the c() function. The c() function combines the elements of a list by considering the lists as its parameter values.

Syntax

c(list1, list2)
Syntax of the c() function

Note: The number of lists that are concatenated should be two or more.

Example

# creating a string and numerical lists
mylist1 <- list("cherry", 'banana', 'orange')
mylist2 <- list(1, 2, 3, 4, 5)
# joining the lists
jointlist <- c(mylist1, mylist2)
jointlist

Explanation

We join the elements of the two lists provided in the code above using the c() function.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources