Get Started

Naming a vector

As a data analyst, it is important to have a clear view on the data that you are using. Understanding what each element refers to is therefore essential.

In the previous exercise, we created a vector with your winnings over the week. Each vector element refers to a day of the week but it is hard to tell which element belongs to which day. It would be nice if you could show that in the vector itself.

You can give a name to the elements of a vector with the names() function. Have a look at this example:

some_vector <- c("John Doe", "poker player")
names(some_vector) <- c("Name", "Profession")

This code first creates a vector some_vector and then gives the two elements a name. The first element is assigned the name Name, while the second element is labeled Profession. Printing the contents to the console yields following output:

          Name     Profession 
    "John Doe" "poker player" 

This is a part of the course

“Introduction to R”

View Course

Exercise instructions

  • The code in the editor names the elements in poker_vector with the days of the week. Add code to do the same thing for roulette_vector.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Poker winnings from Monday to Friday
poker_vector <- c(140, -50, 20, -120, 240)

# Roulette winnings from Monday to Friday
roulette_vector <- c(-24, -50, 100, -350, 10)

# Assign days as names of poker_vector
names(poker_vector) <- c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")

# Assign days as names of roulette_vector

This exercise is part of the course

Introduction to R

BeginnerSkill Level
4.7+
595 reviews

Master the basics of data analysis in R, including vectors, lists, and data frames, and practice R with real data sets.

We take you on a trip to Vegas, where you will learn how to analyze your gambling results using vectors in R. After completing this chapter, you will be able to create vectors in R, name them, select elements from them, and compare different vectors.

Exercise 1: Create a vectorExercise 2: Create a vector (2)Exercise 3: Create a vector (3)Exercise 4: Naming a vector
Exercise 5: Naming a vector (2)Exercise 6: Calculating total winningsExercise 7: Calculating total winnings (2)Exercise 8: Calculating total winnings (3)Exercise 9: Comparing total winningsExercise 10: Vector selection: the good timesExercise 11: Vector selection: the good times (2)Exercise 12: Vector selection: the good times (3)Exercise 13: Vector selection: the good times (4)Exercise 14: Selection by comparison - Step 1Exercise 15: Selection by comparison - Step 2Exercise 16: Advanced selection

What is DataCamp?

Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.

Start Learning for Free