Home / Programs / Naming a vector in R | Question 2
🚀 Programming Example

Naming a vector in R | Question 2

👁 345 Views
💻 Practical Program
📘 Step Learning

If you want to become a good statistician, you have to become lazy. (If you are already lazy, chances are high you are one of those exceptional, natural-born statistical talents.)

In the previous exercises you probably experienced that it is boring and frustrating to type and retype information such as the days of the week. However, when you look at it from a higher perspective, there is a more efficient way to do this, namely, to assign the days of the week vector to a variable!

Just like you did with your poker and roulette returns, you can also create a variable that contains the days of the week. This way you can use and re-use it.

  • A variable days_vector that contains the days of the week has already been created for you.
  • Use days_vector to set the names of poker_vector and roulette_vector.

💻 Program 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)

# The variable days_vector
days_vector <- c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")

# Assign the names of the day to roulette_vector and poker_vector
names(poker_vector) <-  days_vector

# see poker_vector result
poker_vector

# see roulette_vector result
roulette_vector 
                        

🖥 Program Output

> # 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)
> 
> # The variable days_vector
> days_vector <- c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
> 
> # Assign the names of the day to roulette_vector and poker_vector
> names(poker_vector) <-  days_vector
> 
> # see poker_vector result
> poker_vector
   Monday   Tuesday Wednesday  Thursday    Friday 
      140       -50        20      -120       240 
> 
> # see roulette_vector result
> roulette_vector 
[1]  -24  -50  100 -350   10
                            

📘 Explanation

  • A variable days_vector that contains the days of the week has already been created for you.
  • Use days_vector to set the names of poker_vector and roulette_vector.
📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.