If you’re working with lists in R, you’re frequently going to need to add new elements to an existing list. Fortunately, R gives you a couple of options for accomplishing this, including the append () function (adds new elements to the end of a list) and c() (fast way to add multiple elements to a list). We’re going to show you how to use both of these functions to append elements to a list in R and highlight some key points of difference. In addition to this, we’ll explore a couple of edge cases which will swing the correct answer towards one option or the other.
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)
This is a user friendly way to to add items to a list in the sense the syntax is intuitive and easy to understand. It also has good capabilities for handling large lists and unpacking lots of integer values quickly.
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.
Yet More Options for Appending New Elements to a List in R
While the c() function works well and is easy to understand, there’s also an R operator solution: the
[[ operator will append a single element to a list. This lets you to access and modify individual elements of a list by index. One of the key features about the [[ operator is it will automatically expand the list if you assign a value to a new index that is one greater than the current length of the list. This is, however, slower than using c() if you’re trying to append multiple elements.
# create a list with two elements my_list <- list("apple", "banana") # append a new element to the end of the list using the [[ operator my_list[[length(my_list) + 1]] <- "orange"
[[ operator is similar to the [ ] operator but returns the actual element rather than a sub-list containing that element.
Tie Breaker – Insert Elements at a Specific Location
If the position of the inserted element matters, there’s a clear advantage to the append function. You have the option of specifying that the appended element be inserted after a specific element. This is an option in the append function. Here’s an example of this in action.
# create a list with three elements friends <- listt("Ross", "Rachel", "Joey") # append a new element after the second element using the append() function friends <- append(friends, "Chandler", after = 2)
Tie Breaker – Append Multiple Elements To a List
Along the same lines, there’s a clear advantage to using the c() function if you need to append mulitple elements to a list in the same operation. The append function limits you to appending items one at time. Here’s an example of appropriate code using the c() function in R.
# create a list with three elements friends <- list("Ross", "Rachel", "Joey") # append multiple elements to the end of the list using the c() function friends <- c(friends, "Chandler", "Monica", "Phoebe")
While code execution speed is important, it’s important to consider the broader picture when optimizing a particular method. Here are some additional factors that you may want to keep in mind when selecting the right function to use for a high performance loop in R.
- Error handling – When appending elements to a list in R, it’s important to handle potential errors such as out-of-bounds indices or incompatible data types. You can use conditional statements and error handling functions like
tryCatch()to catch and handle errors gracefully.
- Readability – when you’re done with this project, you’re going to move to the next. And the one after that. Until you realize you want to go back and update or recycle part of the code from this project. For this reason, I’ve got a slight preference for the append() and c() approaches listed above. They’re easier to quickly understand. Along the same lines, there’s an advantage to using highly descriptive variable names and generously commenting your code.
Conclusions – Ways to Append in R
We’ve shown you three ways to append new elements to a list data structure in R programming. The append method is the most intuitive, especially for new users of R. Simply apply the append function to your existing vector. This works well for both numeric values and a character vector (aka a string).
The c function is also an excellent choice. This approach has the advantage of being part of the base R core library, so the code runs very quickly. You can append value(s) to a list by combining the existing list with the new value. This is useful for computationally intense data science methods, such as simulation and optimization problems.
For more information about handy functions for manipulating data, check out our functions reference.