Fast Append in R – Quickly Add Elements To A List

Modern computers are fast enough that you rarely need to worry about performance. That being said, certain statistical methods require fast calculations. This is very common for forecasting, statistical modeling, and data interpolation. R’s append() function offers a quick way to accomplish this for lists and vectors, faster than the default concatenation approach.

It should be noted that you don’t *usually* have to do this. The performance improvement for small vectors is likely negligible. But if you’re cranking out a couple hundred thousand values, this helps.

Meet the Append() function

The basic syntax of an append operation is simple.

# append item to list in r
append (first_vector, second_vector)

You are likely already familiar with using concatenate to add elements to a list. While this does a solid job of adding items to a list in R, the append function operates faster.

Append also allows you to specify where to append the values within the list or vector. This will add the items after the named element. For example, the following code will add the new values after the fifth element of the original list.

# r how to append to a list
# insert element after specific number of items
append (first_vector, second_vector, after=5)

You also can directly specifying a list or vector as a source in the append statement.

# r add elements to list using list or vector as source
append (first_vector, c(value1, value2, value3), after=5)

This approach makes for more succinct code.

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

This approach has the disadvantage of being too simple (hah hah). Why not just use the c() function to append values to a list? Syntax would be as follows:

# R using c function to append values to list
mylist <- c(1,2,3,4)
newelem <- 5
mylist <- c(mylist, newelem)

Specific advantages of this approach include

  • You’re working with part of the core R library – this function runs extremely quickly
  • Note that we’ve abstracted the new value into a variable; you can easily create a loop to iterate through another data structure or process (parse a document, query an API, scrape the web) to generate more sophisticated forms of data and pass results to newelem for insertion in the list.

For more information about handy functions for manipulating data, check out our functions reference.