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.
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.
# creating a string and numerical lists mylist1 <- list("cherry", 'banana', 'orange') mylist2 <- list(1, 2, 3, 4, 5) # to print the lists mylist1 mylist2
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.
An element can be added to a list with the append()
function.
append(list, element)
The append()
function takes two parameter values:
list
: The list to which we want to append elements.element
: The element you wish to add.# 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)
We add apple
to the list of elements in the list variable mylist1
and add 6
to the list variable mylist2
.
RELATED TAGS
CONTRIBUTOR
View all Courses