R Tutorial



R MATH


Math in R

R is a powerful language for mathematical computations. It supports basic arithmetic operations, advanced math functions, and statistical calculations.

Basic Arithmetic Operators

R uses common symbols for arithmetic operations:

Operator Description Example
+ Addition 5 + 3 # 8
- Subtraction 10 - 7 # 3
* Multiplication 6 * 4 # 24
/ Division 20 / 5 # 4
^ Exponentiation (Power) 2 ^ 3 # 8
%% Modulo (Remainder) 10 %% 3 # 1
%/% Integer Division 10 %/% 3 # 3

Using Parentheses for Precedence

Parentheses () help control the order of operations:

result <- (5 + 3) * 2
print(result)   # 16 (because addition done before multiplication)
  

Common Mathematical Functions

R provides many built-in math functions:

Function Description Example
abs(x) Absolute value of x abs(-7) # 7
sqrt(x) Square root of x sqrt(25) # 5
round(x, digits) Rounds x to specified digits (default 0) round(3.14159, 2) # 3.14
ceiling(x) Rounds x up to nearest integer ceiling(3.14) # 4
floor(x) Rounds x down to nearest integer floor(3.99) # 3
log(x, base) Logarithm of x with given base (default e) log(100, 10) # 2
exp(x) Exponential of x (e^x) exp(1) # 2.718281
sin(x), cos(x), tan(x) Trigonometric functions (x in radians) sin(pi/2) # 1

Examples

x <- -12.7
abs_x <- abs(x)
print(abs_x)       # 12.7

root_16 <- sqrt(16)
print(root_16)      # 4

rounded_pi <- round(3.14159, 3)
print(rounded_pi)   # 3.142

log_100 <- log(100, 10)
print(log_100)      # 2

angle <- pi / 4
sin_angle <- sin(angle)
print(sin_angle)    # 0.7071068
  

Summary

  • Basic math operators: + - * / ^ %% %/%
  • Use parentheses () to control order of operations.
  • R offers many built-in math functions for everyday calculations.
  • Functions like abs(), sqrt(), log(), and trigonometric functions help in advanced math.

Practice Exercise

  • Calculate the remainder when 123 is divided by 10.
  • Find the square root of 81.
  • Calculate the sine of 90 degrees (Hint: convert degrees to radians first).
  • Round 5.6789 to 1 decimal place.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review