Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

r
communitycreator

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

Onyejiaku Theophilus Chidalu

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
Creating a list

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)
Implementing the append() function

Explanation

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

RELATED TAGS

r
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring