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

Variable assignment in R Question 3

👁 778 Views
💻 Practical Program
📘 Step by 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

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.

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.