How to Add/Append an Element to a List in R [2 Ways]

Diagram of Add/Append an Element to a List in R

Here are two ways to add/append an element to a list in R.

  1. Using append() function
  2. Using c() function

Method 1: Use the append() method

The main way to add or append an element to a list in R is to use the “append()” function. The append() function accepts three parameters input list, a string or list you wanted to append, and position. Then, the element is appended at the end of the list in the specified order.

Syntax

append(data, values, after = length(data))

Parameters

  1. data: It is a list or vector.
  2. values: It is a vector or list to be included in the modified vector.
  3. after: It is a subscript, after which the values are to be appended.

Example 1: Simple R code to add/append an element to a list

list1 <- list(a = 1, b = 2, c = 3)
list2 <- list(d = 4)

appended_list <- append(list1, list2)
print(appended_list)

Output

$a
[1] 1

$b
[1] 2

$c
[1] 3

$d
[1] 4

Example 2: Appending an element at the specific position

To append an element at a specific position, use the “after” parameter of the “append()” function. You can specify the position where you want to add the element using the after parameter.

lt <- list("SBF", "Alameda")
lt2 <- append(lt, "FTX", after = 1)
print(lt2)

Output

[[1]]
[1] "SBF"

[[2]]
[1] "FTX"

[[3]]
[1] "Alameda"

To add multiple elements to a list, you can check out the 4 ways to add multiple elements to a list article.

Method 2: Use the c() function

You can use the “c()” function to “append values to a list”. It is a straightforward approach to append elements to the list.

my_list <- list(1, 2, 3)

my_list <- c(my_list, 4)

print(my_list)

Output

[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3

[[4]]
[1] 4

Conclusion

Using append():

  1. When to Use: When you need to insert new elements at a specific position within the list.
  2. Why: Offers control over the position at which new elements are added.

Using c():

  1. When to Use: For straightforward appending of elements or concatenating two lists.
  2. Why: Simple, easy to understand, and good for quick operations.

If you’re just getting started with R, the c() function is probably the easiest to understand and use. It’s straightforward and doesn’t require an understanding of indexing or positional arguments.

The append() function lets you specify where to insert new elements. This makes it suitable for users who have a good understanding of list structures and need more control over element positioning.

Related posts

Add or Append Elements to a Vector in R

Append Multiple Elements to a Vector in R

Append an Element to Empty List in R

Append or Concatenate String in R

Append Data Frames in R

Add/Append Multiple Elements to a List in R

Leave a Comment