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 every single item in your 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 in large lists, this iteration of the append function helps make your code run smoother with each new element in your new list.
Meet the Append() function
The basic syntax of the R object append method is simple.
# append item to list in r
append (first_vector, second_vector)
You are likely already familiar with using concatenate to add multiple elements to a given list. While this does a solid job of adding individual elements to an existing list in R, the append function operates faster, and has better list comprehension for working with large lists and lots of integer values.
R append to list also allows you to specify where to append the values within the list element 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 append function runs extremely quickly, appending multiple elements to the given list in a sequence very quickly, as apposed to a generic apply function or regular expression
- 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 existing list. This helps if you are trying to combine a different data type into your list object, or create a new list with individual elements of a different type in R.
For more information about handy functions for manipulating data, check out our functions reference.