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.

 

 

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.

 

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.


2 Comments. Leave new

  • Hi, which packages do you use? I tried but RStudio pulls out the following error:

    Error in as.dataframe(as.list(vectorname)) :
    could not find function “as.dataframe”

    I use the newest version of R and RStudio

    Thanks!

    Reply

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.

Top