Menu
Coddy logo textTech

Arithmetic Operators

Part of the Fundamentals section of Coddy's R journey — lesson 12 of 78.

Arithmetic operators let you perform mathematical calculations in R. These operators work with numeric values and follow the same mathematical rules you already know.

R supports five basic arithmetic operators:

OperatorOperationExampleResult
+Addition5 + 38
-Subtraction10 - 46
*Multiplication6 * 742
/Division15 / 35
^Exponentiation2 ^ 38

You can use these operators directly with numbers or with variables that contain numeric values:

price <- 25
quantity <- 4
total <- price * quantity

R follows standard mathematical order of operations: exponentiation first, then multiplication and division, and finally addition and subtraction. Use parentheses to control the order when needed, just like in regular math.

challenge icon

Challenge

Easy

Calculate the total cost of a shopping trip using arithmetic operators.

You are provided with the following variables:

apples <- 6
apple_price <- 1.5
milk_cartons <- 2
milk_price <- 3.25
discount <- 5

Calculate and store the following values:

  1. Create a variable called apples_total that stores the cost of all apples (quantity multiplied by price)
  2. Create a variable called milk_total that stores the cost of all milk cartons (quantity multiplied by price)
  3. Create a variable called subtotal that stores the sum of apples_total and milk_total
  4. Create a variable called final_total that stores the subtotal minus the discount

Use the print() function to display apples_total, milk_total, subtotal, and final_total in that exact order.

Cheat sheet

R supports five basic arithmetic operators:

OperatorOperationExampleResult
+Addition5 + 38
-Subtraction10 - 46
*Multiplication6 * 742
/Division15 / 35
^Exponentiation2 ^ 38

You can use these operators with numbers or variables:

price <- 25
quantity <- 4
total <- price * quantity

R follows standard mathematical order of operations: exponentiation first, then multiplication and division, and finally addition and subtraction. Use parentheses to control the order when needed.

Try it yourself

# Given variables
apples <- 6
apple_price <- 1.5
milk_cartons <- 2
milk_price <- 3.25
discount <- 5

# TODO: Write your code below
# 1. Calculate apples_total (quantity * price)
# 2. Calculate milk_total (quantity * price)
# 3. Calculate subtotal (sum of apples_total and milk_total)
# 4. Calculate final_total (subtotal minus discount)

# Print the results in order: apples_total, milk_total, subtotal, final_total
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals