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 listsmylist1 <- list("cherry", 'banana', 'orange')mylist2 <- list(1, 2, 3, 4, 5)# to print the listsmylist1mylist2
Explanation
-
Lines 2–3: We create two list variables
mylist1andmylist2that 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 listsmylist1 <- list("cherry", 'banana', 'orange')mylist2 <- list(1, 2, 3, 4, 5)# to print the listsappend(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.