R append to list: How to Append Element in R List

R list is a data structure having elements of different data types. To create a list in R, use the list() function. To access the list, use the indexing. You can use integer, logical, or character vectors for indexing.  List in R can be modified that means you can add, update, or delete the list components.

R append to list

To append an item in the R List, use the list.append() function. You can use the concatenate approach to add components to a list. While concatenate does a great job of adding elements to the R list, the append() function operates faster.

The append() function also allows us to define where to append the values within the list or vector. This will add the elements after the named element.

Syntax

list.append(.data, ...)

Parameters

.data

It is a list or vector.

...

It is a vector or list to append after x.

Example

To append an element to the list at the last position, use the third parameter called after and specify the index, after which you want to append a new element.

rv1 <- c(10, 20, 30, 40)
rv2 <- append(rv1, 50, after = 40)
print(rv2)

Output

Rscript Pro.R
[1] 10 20 30 40 50

In this example, we are appending an item after the specific component. In our case, it is 40, and it is last.

Use of the c() function to append to lists in R

You can use the c() function to append values to a list. It is a straightforward approach to append elements in the R List.

rv1 <- c(10, 20, 30, 40)
newel <- 50
rv1 <- c(rv1, newel)
print(rv1)

Output

[1] 10 20 30 40 50

That is it for this R append to list example.

See also

R Matrix

R Array

Leave a Comment