Convert Named Vector to Data Frame in R (Example)


In this R programming tutorial you’ll learn how to convert a vector with names to the data.frame class.

The page looks as follows:

Let’s do this.


Creation of Example Data

First, let’s construct some example data:

vec <- 1:5                          # Create example vector
names(vec) <- letters[1:5]
vec                                 # Print vector
# a b c d e 
# 1 2 3 4 5

As you can see based on the previous output of the RStudio console, our example data is a named vector with five elements.


Example: Converting Named Vector to Data Frame Using data.frame & as.list Functions

This Example illustrates how to use the data.frame and as.list functions to convert a named vector to the data.frame data type. Have a look at the following R code:

data <- data.frame(as.list(vec))    # Convert to data.frame
data                                # Print data
#   a b c d e
# 1 1 2 3 4 5

As you can see in the previous output, our named vector was changed to become a data.frame.


Video & Further Resources

Have a look at the following video of my YouTube channel. In the video, I show the R codes of this article in RStudio.


The YouTube video will be added soon.


In addition, you might want to read the related R programming tutorials of this homepage:


In summary: In this R programming tutorial you learned how to change a named vector to a data frame. Please let me know in the comments section, in case you have any further questions.


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.