R – Add/Append Item to List

To add an item to a list in R programming, call append() function and pass the list and item as arguments in the function call.

In this tutorial, we will learn how to add or append an element to a list in R, using append() function, with the help of example programs.

Syntax

The syntax to of append() function is

</>
Copy
append(myList, item, after = index)

The append() function appends the item item after specified position index in the list myList.

after parameter is optional. If no index is provided for after parameter, the item is appended at end of the list.

append() function does not modify the original list, but returns a new list.

Examples

In the following program, we will create a list with some initial values, and then append items to it using append() function.

example.R

</>
Copy
myList <- list("Sunday", "Monday")
myList <- append(myList, "Tuesday")
print(myList)

Output

[[1]]
[1] "Sunday"

[[2]]
[1] "Monday"

[[3]]
[1] "Tuesday"

Now, let us create a list with some initial values, and append the element at specific index 2.

example.R

</>
Copy
myList <- list("Sunday", "Monday", "Wednesday")
myList <- append(myList, "Tuesday", after = 2)
print(myList)

Output

[[1]]
[1] "Sunday"

[[2]]
[1] "Monday"

[[3]]
[1] "Tuesday"

[[4]]
[1] "Wednesday"

Conclusion

In this R Tutorial, we learned how to append an item to a list in R programming using append() function, with the help of examples.