0
0
R Programmingprogramming~5 mins

Named vectors in R Programming

Choose your learning style9 modes available
Introduction

Named vectors let you give names to each value in a list of numbers or words. This makes it easier to find and understand the data.

You want to label each number in a list so you remember what it means.
You need to access values by name instead of by position.
You want to print data with clear labels for better understanding.
You are working with small sets of related data like scores or measurements.
You want to make your code easier to read by using meaningful names.
Syntax
R Programming
vector <- c(name1 = value1, name2 = value2, name3 = value3)

Use the c() function to create a vector with names.

Each name is followed by an equals sign = and then the value.

Examples
This creates a named vector with three subjects and their scores.
R Programming
scores <- c(math = 90, science = 85, english = 88)
Here, days of the week are names for temperature values.
R Programming
temps <- c(Monday = 22, Tuesday = 24, Wednesday = 20)
Named vector with color names and their hex codes as strings.
R Programming
colors <- c(red = "#FF0000", green = "#00FF00", blue = "#0000FF")
Sample Program

This program creates a named vector of fruits with quantities. It prints the whole vector, then the quantity of bananas, and finally the names of all fruits.

R Programming
fruits <- c(apple = 3, banana = 5, orange = 2)
print(fruits)
print(fruits["banana"])
print(names(fruits))
OutputSuccess
Important Notes

You can access values by their names using square brackets and quotes, like vector["name"].

Names help you avoid mistakes when the order of values changes.

Named vectors work well for small sets of data but for bigger data, consider other structures like data frames.

Summary

Named vectors let you label each value for easier access and understanding.

You create them using c(name = value) syntax.

Access values by name using vector["name"].