Numbers and Mathematics in R

📘 Introduction

Numbers are one of the most fundamental data types in R. They are used for arithmetic calculations, statistical analysis, scientific computing, financial modeling, and data analysis. R provides a rich collection of built-in mathematical operators and functions, allowing you to perform everything from basic arithmetic to advanced mathematical computations.

Information

R supports different types of numeric values, including integers, doubles (decimal numbers), complex numbers, and special numeric values such as Inf, -Inf, and NaN.

đŸŽ¯ Why Learn Numbers and Mathematics?

  • Perform arithmetic calculations.
  • Analyze numerical datasets.
  • Build statistical and machine learning models.
  • Solve mathematical problems efficiently.
  • Support scientific and engineering applications.

đŸ”ĸ Numeric Data Types

TypeDescriptionExample
IntegerWhole numbers.25L
DoubleDecimal numbers (default numeric type).25.5
ComplexNumbers with imaginary parts.3 + 2i

Creating Numeric Values

integerNum <- 25L
decimalNum <- 25.75
complexNum <- 3 + 2i

print(integerNum)
print(decimalNum)
print(complexNum)

➕ Basic Arithmetic Operations

R supports standard arithmetic operators for performing mathematical calculations.

Arithmetic Operations

a <- 20
b <- 6

print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a ^ b)
print(a %% b)
print(a %/% b)

Output

Console Output

[1] 26
[1] 14
[1] 120
[1] 3.333333
[1] 64000000
[1] 2
[1] 3

📐 Mathematical Functions

FunctionDescriptionExample
abs()Absolute value.abs(-10)
sqrt()Square root.sqrt(25)
exp()Exponential function.exp(1)
log()Natural logarithm.log(10)
log10()Base-10 logarithm.log10(100)
factorial()Factorial of a number.factorial(5)

Using Mathematical Functions

print(abs(-15))
print(sqrt(81))
print(exp(1))
print(log(10))
print(log10(1000))
print(factorial(6))

🔄 Rounding Numbers

R provides several functions for rounding numerical values.

FunctionDescription
round()Rounds to a specified number of digits.
floor()Rounds down.
ceiling()Rounds up.
trunc()Removes the decimal part.

Rounding Functions

value <- 12.78

print(round(value))
print(round(value, 1))
print(floor(value))
print(ceiling(value))
print(trunc(value))

📈 Statistical Functions

R includes many built-in statistical functions for analyzing numeric data.

Basic Statistics

numbers <- c(10, 20, 30, 40, 50)

print(sum(numbers))
print(mean(numbers))
print(median(numbers))
print(min(numbers))
print(max(numbers))
print(range(numbers))

Output

Console Output

[1] 150
[1] 30
[1] 30
[1] 10
[1] 50
[1] 10 50

📊 Random Number Generation

R provides functions for generating random numbers useful for simulations, testing, and statistical analysis.

Generating Random Numbers

set.seed(100)

runif(5)

sample(1:10, 5)

rnorm(5)

📏 Mathematical Constants

ConstantDescription
piValue of ΀ (Pi).
InfPositive infinity.
-InfNegative infinity.
NaNNot a Number.

Using Mathematical Constants

print(pi)
print(Inf)
print(-Inf)
print(NaN)

🧮 Trigonometric Functions

R includes functions for performing trigonometric calculations. Angles are measured in radians.

Trigonometric Functions

angle <- pi / 4

print(sin(angle))
print(cos(angle))
print(tan(angle))

📐 Working with Complex Numbers

R supports complex arithmetic using the imaginary unit i.

Complex Numbers

z <- 4 + 3i

print(Mod(z))
print(Re(z))
print(Im(z))
print(Conj(z))

🔄 Vectorized Mathematical Operations

Mathematical operations in R are vectorized, meaning they operate on every element of a vector automatically.

Vectorized Calculations

numbers <- c(2,4,6,8)

print(numbers + 5)
print(numbers * 2)
print(numbers^2)
print(sqrt(numbers))

🌍 Real-World Example

The following program calculates the total, average, highest, and lowest monthly sales.

Monthly Sales Analysis

sales <- c(45000, 52000, 49000, 61000, 58000)

totalSales <- sum(sales)
averageSales <- mean(sales)
highestSales <- max(sales)
lowestSales <- min(sales)

print(totalSales)
print(averageSales)
print(highestSales)
print(lowestSales)

📊 Mathematics Workflow

Create Numeric Data
Perform Calculations
Apply Mathematical Functions
Analyze Results
Display Output

📋 Arithmetic Operators vs Mathematical Functions

FeatureArithmetic OperatorsMathematical Functions
PurposeBasic calculations.Advanced mathematical operations.
Examples+, -, *, /sqrt(), log(), exp()
ComplexitySimple operations.Specialized calculations.

âš ī¸ Common Mistakes

MistakeExplanationSolution
Using integer division instead of normal division%/% returns only the quotient.Use / for decimal division.
Taking the square root of negative numbersReturns NaN unless using complex numbers.Use complex values when appropriate.
Confusing ^ with multiplication^ performs exponentiation.Use * for multiplication.
Ignoring vectorized operationsUnnecessary loops may reduce readability.Take advantage of R's vectorized calculations.

💡 Best Practices

  • Use built-in mathematical functions whenever possible.
  • Prefer vectorized operations over explicit loops.
  • Use meaningful variable names for calculations.
  • Set a random seed using set.seed() when reproducible random numbers are required.
  • Choose the appropriate rounding function based on your requirements.

Best Practice

R is optimized for numerical and statistical computing. Leveraging its built-in mathematical functions and vectorized operations results in cleaner, faster, and more reliable code.

📝 Summary

Numbers and mathematics form the foundation of programming in R. You learned about numeric data types, arithmetic operators, mathematical and statistical functions, rounding methods, random number generation, mathematical constants, trigonometric functions, complex numbers, and vectorized calculations. Mastering these concepts enables you to perform efficient numerical analysis, statistical computations, and scientific programming using R.

>>"Mathematics is at the heart of R, empowering you to transform raw numbers into meaningful insights."