Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

append()
r
communitycreator

How to add an item before a specified index in a list in R

Onyejiaku Theophilus Chidalu

Overview

A list in R is simply a collection of ordered and changeable data. A list contains different data types such as strings or numbers. The elements contained in a given list are referred to as the item of the list.

Creating a list

We use the list() function to create a list in R. This function takes the list of items you want on the list as parameters.

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 using the list() function

Code Explanation

We create two list variables mylist1 and mylist2 that have strings and numbers respectively.

Adding an item to the right of a specified index of a list

Remember that in R, the first index of any given character is 1. For example, the “H” in “Hello” has the index value 1, the second character “e” has index value 2, and so on.

Now, to add an item to the list in R, we use the append() function. To add an item to the right of a specified index in a code, we add after = index number inside the append function.

Syntax

append(list, item, after = index number)
Syntax for the append() function

Example

# creating a string and numerical lists
mylist <- list("cherry", 'banana', 'apple')

# implementing the append() function
append(mylist, "orange", after = 2)
Implementing the append() function

Explanation

In the code above we create a list mylist, and add the item "orange" to the list right after the second item, “banana”.

RELATED TAGS

append()
r
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring