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
# [[1]]
# [1] 5 4 3 2 1
# 
# [[2]]
# [1] 10 11 12 13 14 15
# 
# [[3]]
# [1] 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
#  [1]  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
#  [1]  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.

 

The YouTube video will be added soon.

 

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.

 

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.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top