Create a Vector with Names in R (Example)

 

In this tutorial you’ll learn how to create a named vector object in R programming.

Table of contents:

Let’s dive right into the example:

 

Example: Construct Vector with Names Using setNames() Function

This example explains how to create a vector with names in the R programming language.

For this task, we first have to create a vector containing numerical values…

my_values <- 1:5                              # Create vector of values
my_values                                     # Print vector of values
# [1] 1 2 3 4 5

…and a vector containing the corresponding names to our numbers:

my_names <- letters[1:5]                      # Create vector of names
my_names                                      # Print vector of names
# [1] "a" "b" "c" "d" "e"

Note that the length of the vector of numbers and the length of the vector of names needs to be the same.

In the next step, we can apply the setNames function to combine our numerical values and our names:

my_vector <- setNames(my_values, my_names)    # Create vector of values & names
my_vector                                     # Print vector of values & names
# a b c d e 
# 1 2 3 4 5

The previous output of the RStudio console shows that we have created a named vector object in R.

 

Video, Further Resources & Summary

Do you want to learn more about the construction of a named vector object? Then you could have a look at the following video on my YouTube channel. I’m explaining the R programming codes of the present article in the video.

 

The YouTube video will be added soon.

 

In addition, you may want to have a look at the related tutorials on this website.

 

This page has explained how to construct a named vector in R. Let me know in the comments section below, in case you have 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.


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