Combine List of Vectors to Single Vector in R (2 Examples)
In this R tutorial you’ll learn how to convert a list of vectors to a single vector object.
The content of the article looks as follows:
Let’s do this.
Creation of Exemplifying Data
Have a look at the following example data:
my_list <- list(5:1, # Create example list 10:15, 25) my_list # Print example list # [] #  5 4 3 2 1 # # [] #  10 11 12 13 14 15 # # [] #  25
The previous output of the RStudio console shows the structure of our example data – It’s a list object consisting of three list elements.
Example 1: Convert List of Vectors to Single Vector Using unlist() Function
In Example 1, I’ll explain how to combine the vector objects in our list to a single vector object using the basic installation of the R programming language.
For this, we can apply the unlist function as shown below:
my_vec1 <- unlist(my_list) # Apply unlist() function my_vec1 # Print vector #  5 4 3 2 1 10 11 12 13 14 15 25
As you can see based on the previous output, we have created a vector object called my_vec1 that contains all values of our input list.
Example 2: Convert List of Vectors to Single Vector Using Reduce() & c() Functions
This example shows how to use the Reduce & c functions to unlist our data.
Have a look at the following R code:
my_vec2 <- Reduce(c, my_list) # Apply Reduce() function my_vec2 # Print vector #  5 4 3 2 1 10 11 12 13 14 15 25
The result is exactly the same as in Example 1. So whether you want to use the unlist function or the Reduce and c functions is a matter of taste!
Video & Further Resources
Would you like to know more about the convert a list of vectors to a single vector object? Then you may watch the following video which I have published on my YouTube channel. In the video, I’m explaining the topics of this page in a live session.
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
In addition, you may read the other tutorials on my homepage. Please find a selection of related tutorials on topics such as data conversion, vectors, lists, and character strings below.
- Convert List of Vectors to Data Frame in R
- Concatenate Vector of Character Strings
- Convert Vector to List in R
- Create List of Vectors in R
- R Programming Tutorials
In summary: In this article you have learned how to transform several vectors in a list to a single vector in the R programming language. Please let me know in the comments section below, if you have additional questions.
Statistics Globe Newsletter