contact@a2zlearners.com

1.3. Writing Code

1.3.3. Arithmetic Operators in R

Arithmetic operators are used for performing basic mathematical operations like addition, subtraction, multiplication, and division. In R, these operators are vectorized, meaning they apply the operation element-by-element across vectors automatically.

  • Addition (+)Adds values together Combines two numbers or corresponding elements of two vectors by adding them.

    • 5 + 1015
  • Subtraction (-)Subtracts one value from another Subtracts the second value or vector from the first.

    • 100 - 2575
  • Multiplication (*)Multiplies values Multiplies numbers or vector elements positionally.

    • 6 * 742
  • Division (/)Divides values Divides the first number or vector by the second, element by element.

    • 20 / 54
  • Exponentiation (^)Raises values to a power Elevates a number or vector element to the power of another number.

    • 3 ^ 481
  • Modulus (%%)Returns the remainder after division Gives the remainder from dividing the first value by the second.

    • 9 %% 41
  • Integer Division (%/%)Returns only the integer part of division Discards any remainder and returns the whole number quotient.

    • 17 %/% 44

**Examples usage Arithmetic Operators in different cases**

**1. Inside `mutate()` within Data Frames**

Operators are frequently used inside mutate() to create derived variables:

df <- df %>%
  mutate(BMI = weight_kg / (height_m ^ 2))

This utilizes / and ^ to compute body mass index row-wise.

**2. With Matrices and Arrays**

Arithmetic operators work element-wise across matrices and arrays too:

A <- matrix(c(1, 2, 3, 4), nrow = 2)
B <- matrix(c(10, 20, 30, 40), nrow = 2)

A + B     # adds matrices element-wise
A * B     # multiplies each element

**3. In Conditional Statements and Filtering**

You can embed arithmetic inside ifelse(), filter(), or case_when() to drive logic:

df %>%
  mutate(Status = ifelse(score / 100 > 0.6, "Pass", "Fail"))

**4. Within User-Defined Functions**

Arithmetic operators are heavily used in custom logic:

discount_price <- function(price, discount_pct) {
  price - (price * discount_pct / 100)
}
discount_price(100, 20)  # returns 80

**5. Combined with `across()` for Multiple Columns**

Apply arithmetic to several columns at once:

df %>%
  mutate(across(c(var1, var2), ~ . * 2))

**6. Dynamic Column Selection + Arithmetic**

You can use dplyr::rowwise() for row-specific calculations across multiple columns:

df %>%
  rowwise() %>%
  mutate(Total = sum(c_across(starts_with("Q"))))

**7. Inside Loops or `apply()` Functions**

When working outside tidyverse, you can use arithmetic with sapply() or lapply():

sapply(1:5, function(x) x^2 + 3)

**8. Vector Recycling in Unequal Lengths**

R allows arithmetic between vectors of unequal lengths through recycling:

c(10, 20, 30) + c(1)     # returns 11, 21, 31

(But raises a warning if the longer vector length is not a multiple of the shorter one.)


**8. Error Handling and Warnings with Arithmetic Operators**

  • Division by Zero:
    Dividing by zero returns Inf, -Inf, or NaN (not an error, but a warning may be shown).

    10 / 0      # Inf
    -5 / 0      # -Inf
    0 / 0       # NaN
    
  • Operations with NA or NULL:
    Arithmetic with NA returns NA. Use na.rm = TRUE in functions like sum() to ignore missing values.

    c(1, NA, 3) + 2   # 3 NA 5
    sum(c(1, NA, 3))              # NA
    sum(c(1, NA, 3), na.rm = TRUE) # 4
    
  • Vector Recycling Warnings:
    If vectors are of unequal length and the longer is not a multiple of the shorter, R will recycle with a warning.

    c(1, 2, 3) + c(10, 20)  # Warning: longer object length is not a multiple of shorter object length
    # Result: 11 22 13
    
  • Non-numeric Data:
    Arithmetic on non-numeric types (e.g., character) will result in an error.

    "a" + 1   # Error in "a" + 1 : non-numeric argument to binary operator
    
  • Overflow and Underflow:
    Extremely large or small numbers may result in Inf, -Inf, or 0.

    1e308 * 1e10   # Inf
    1e-308 / 1e10  # 0
    

Tip:
Use is.na(), is.nan(), is.infinite() to check for problematic results, and wrap calculations in tryCatch() for robust error handling in scripts.


**Resource download links**

1.3.3.-Arithmetic-Operators-in-R.zip