R Math

➗📐 R Math – Complete Tutorial
In R, mathematical operations are used for data analysis, statistics, scientific computing, and machine learning.
R provides built-in math operators and functions that work efficiently on numbers, vectors, and matrices.
1️⃣ Basic Mathematical Operators in R
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | Addition | 5 + 3 | 8 |
- | Subtraction | 5 - 3 | 2 |
* | Multiplication | 5 * 3 | 15 |
/ | Division | 5 / 2 | 2.5 |
^ | Power | 5 ^ 2 | 25 |
%% | Modulus | 5 %% 2 | 1 |
%/% | Integer Division | 5 %/% 2 | 2 |
2️⃣ Mathematical Functions in R ⭐
Square Root
Absolute Value
Power Function
3️⃣ Rounding Functions ⭐
| Function | Purpose | Example | Result |
|---|---|---|---|
round() | Round to nearest | round(3.6) | 4 |
floor() | Round down | floor(3.6) | 3 |
ceiling() | Round up | ceiling(3.2) | 4 |
trunc() | Remove decimal | trunc(3.9) | 3 |
4️⃣ Logarithmic & Exponential Functions ⭐
5️⃣ Trigonometric Functions ⭐
📌 Angles are in radians, not degrees.
6️⃣ Mathematical Operations on Vectors ⭐
R is vectorized, meaning operations apply to all elements.
7️⃣ Sum, Mean, Min, Max ⭐
8️⃣ Cumulative Math Functions ⭐
9️⃣ Mathematical Constants in R
| Constant | Meaning |
|---|---|
pi | π (3.141593) |
Inf | Infinity |
-Inf | Negative infinity |
NaN | Not a number |
🔟 Handling NA in Math ⚠️
📌 Always use na.rm = TRUE in real data.
1️⃣1️⃣ Operator Precedence ⭐
Order of execution:
^*,/+,-
1️⃣2️⃣ Common Mistakes ❌
❌ Forgetting vectorization
❌ Ignoring NA values
❌ Confusing / with %/%
❌ Using degrees instead of radians in trig
📌 Interview Questions & MCQs
Q1. What does %/% do in R?
A) Modulus
B) Division
C) Integer division
D) Power
✅ Answer: C
Q2. Output of 5 %% 2?
A) 2
B) 2.5
C) 1
D) 0
✅ Answer: C
Q3. Which function calculates square root?
A) root()
B) sqrt()
C) pow()
D) sq()
✅ Answer: B
Q4. Which function ignores NA values?
A) remove.na()
B) na.rm = TRUE
C) ignore.na()
D) skip.na()
✅ Answer: B
Q5. What is the value of sin(pi/2)?
A) 0
B) 1
C) −1
D) π
✅ Answer: B
🔥 Real-Life Use Cases
✔ Statistical analysis
✔ Financial calculations
✔ Scientific computing
✔ Data science & ML
✔ Engineering problems
✅ Summary
R supports powerful math operations
Vectorized calculations make R fast
Many built-in math & statistical functions
Handle NA carefully
Essential for R exams, interviews & data analysis
