Convert Vector to List in R (Example)

 

In this R article you’ll learn how to convert a vector object to a list.

The article will consist of one example for the conversion of vectors (or arrays) to lists. To be more specific, the tutorial contains the following topics:

Here’s the step-by-step process…

 

Construction of Example Data

Consider the following example data:

my_vec <- LETTERS[1:5]            # Example vector
my_vec                            # Print vector
# "A" "B" "C" "D" "E"

Have a look at the previously shown output of the RStudio console. It shows that the example data is a simple vector consisting of upper case letters ranging from A to E.

 

Example: Converting Vector to List Using as.list Function

In this Example, I’ll explain how to transform our example vector to a list in R.

my_list <- as.list(my_vec)        # Apply as.list function
my_list                           # Print list
# [[1]]
# [1] "A"
# 
# [[2]]
# [1] "B"
# 
# [[3]]
# [1] "C"
# 
# [[4]]
# [1] "D"
# 
# [[5]]
# [1] "E"

As you can see based on the previously shown output of the RStudio console, each element of our vector was converted as its own list element (i.e. our list has the same length as our input vector).

 

Video & Further Resources

In case you need more info on the R programming codes of this tutorial, you may want to watch the following video of my YouTube channel. I’m explaining the R syntax of this tutorial in the video:

 

The YouTube video will be added soon.

 

Furthermore, you might have a look at the other articles on my homepage. You can find a selection of tutorials below:

 

This article explained how to change the vector format to a list in R. If you have any additional comments and/or questions, don’t hesitate to tell me about it in the comments below.

 



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