How to add an element to a list using the append() function in R

Overview

A list in R is a collection of ordered and changeable data. A list can contain different data types ranging from strings to numbers. These ordered different data types in a list are referred to as the list’s elements.

Before we add an element to a list, let’s first look at how to create a list in R.

Creating a list

We use the list() function to create a list in R. This function takes only the list of elements you want on the list as its parameter value.

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

  • Lines 2–3: We create two list variables mylist1 and mylist2 that contain string and number elements respectively.

  • Lines 6–7: We print the two list variables that we created.

How to add an element to a list using the append() function

An element can be added to a list with the append() function.

Syntax

append(list, element)

Parameter value

The append() function takes two parameter values:

  • list: The list to which we want to append elements.
  • element: The element you wish to add.

Example

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

Explanation

We add apple to the list of elements in the list variable mylist1 and add 6 to the list variable mylist2.

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
🎁 G i v e a w a y
30 Days of Code
Complete Educative’s daily coding challenge every day in September, and win exciting Prizes.

Free Resources