Home / Programs / Variable assignment in R Question 3
🚀 Programming Example

Variable assignment in R Question 3

👁 778 Views
💻 Practical Program
📘 Step Learning

Every tasty fruit basket needs oranges, so you decide to add six oranges. As a data analyst, your reflex is to immediately create the variable my_oranges and assign the value 6 to it. Next, you want to calculate how many pieces of fruit you have in total. Since you have given meaningful names to these values, you can now code this in a clear way:

my_apples + my_oranges

💻 Program Code

# Assign a value to the variables my_apples and my_oranges
my_apples <- 5
my_oranges <- 6

# Add these two variables together
my_apples + my_oranges

# Create the variable my_fruit
my_fruit <- my_apples + my_oranges
                        

🖥 Program Output

> # Assign a value to the variables my_apples and my_oranges
> my_apples <- 5
> my_oranges <- 6
> 
> # Add these two variables together
> my_apples + my_oranges
[1] 11
> 
> # Create the variable my_fruit
> my_fruit <- my_apples + my_oranges
> # Assign a value to the variables my_apples and my_oranges
> my_apples <- 5
> my_oranges <- 6
> 
> # Add these two variables together
> my_apples + my_oranges
[1] 11
> 
> # Create the variable my_fruit
> my_fruit <- my_apples + my_oranges
> 
> # see result
> my_fruit
[1] 11
                            

📘 Explanation

  • Assign to my_oranges the value 6.
  • Add the variables my_apples and my_oranges and have R simply print the result.
  • Assign the result of adding my_apples and my_oranges to a new variable my_fruit.
📚 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.