Chapter 13: R Math

R Math (mathematical functions and operations in R).

R was literally designed for mathematics and statistics, so its math support is excellent — fast, vectorized (works on whole vectors at once), and packed with built-in functions. You rarely need external packages for basic/advanced math.

I’m going to explain it like your friendly offline teacher: slow, detailed, with tons of copy-paste examples you can run right now in RStudio, explanations of why things work this way, common traps, and 2026 modern usage tips.

1. First: Basic Arithmetic Operators (The Calculator Part)

These are the most used every day:

Operation Symbol Example code Result Notes
Addition + 5 + 3 8
Subtraction 10 – 4.2 5.8
Multiplication * 6 * 7 42
Division / 100 / 4 25
Exponentiation ^ or ** 2 ^ 10 or 3 ** 4 1024 or 81 Both work, ^ is more common
Modulo (remainder) %% 17 %% 5 2 Very useful in loops/indexing
Integer division %/% 17 %/% 5 3 Floor division

Vectorized magic (this is why R feels powerful):

R

2. Most Important Math Functions (Base R – No Package Needed)

Run ?Math in R console to see the full list — here are the ones you use 90% of the time:

Function What it does Example Result / Notes
abs() Absolute value abs(-7.2) 7.2
sqrt() Square root sqrt(144) 12
exp() Exponential function (e^x) exp(1) ≈2.718
log() Natural log (ln) log(100) ≈4.605
log10() Log base 10 log10(1000) 3
log2() Log base 2 log2(8) 3
round() Round to n decimals round(3.14159, 2) 3.14
floor() Largest integer ≤ x floor(3.9) 3
ceiling() Smallest integer ≥ x ceiling(3.1) 4
trunc() Truncate toward zero trunc(-3.9) -3
sign() Sign: -1 / 0 / 1 sign(c(-5, 0, 7)) -1 0 1
factorial() n! factorial(5) 120
choose() Binomial coefficient nCr choose(5, 2) 10

Trigonometric & hyperbolic (in radians!):

R

3. Special Math Constants Built-in

R

No built-in golden ratio, but easy:

R

4. Vectorized = Super Fast & Clean

This is R’s superpower:

R

5. Common Gotchas & Floating-Point Reality

Floating-point arithmetic is not exact:

R

Division by zero:

R

6. Your Mini Practice Session (Copy → Run Now!)

R

7. Quick Summary Cheat-Sheet

  • Arithmetic: + – * / ^ %% %/%
  • Roots & logs: sqrt(), log(), log10(), log2(), exp()
  • Rounding: round(), floor(), ceiling(), trunc()
  • Trig: sin(), cos(), tan(), asin(), etc. (radians!)
  • Constants: pi, exp(1)
  • Vectorized → apply to whole lists/vectors automatically
  • Compare floats → all.equal() or small epsilon, never ==

Want to go deeper?

  • Special functions (gamma(), beta(), bessel*()) ?
  • Matrix algebra (%*%, solve(), eigen()) ?
  • Or practice building a small math tool (BMI calculator, compound interest)?

Just tell me — next whiteboard page is ready! ☕📐🚀

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *