Arithmetic operators in R are essential tools for performing mathematical calculations. They allow you to manipulate numeric data efficiently, making R a powerful language for statistical computing and data analysis.
R provides several fundamental arithmetic operators:
+
: Addition-
: Subtraction*
: Multiplication/
: Division^
or **
: Exponentiation%%
: Modulus (remainder)%/%
: Integer divisionLet's explore how to use these operators with some practical examples:
# Basic arithmetic
a <- 10
b <- 3
sum <- a + b # Addition: 13
difference <- a - b # Subtraction: 7
product <- a * b # Multiplication: 30
quotient <- a / b # Division: 3.333333
# Exponentiation
power <- a ^ 2 # 100 (10 squared)
# Modulus
remainder <- a %% b # 1 (remainder of 10 divided by 3)
# Integer division
int_quotient <- a %/% b # 3 (integer part of 10 divided by 3)
R's arithmetic operators work seamlessly with vectors, allowing for efficient element-wise operations:
# Vector arithmetic
vec1 <- c(1, 2, 3, 4, 5)
vec2 <- c(2, 4, 6, 8, 10)
vec_sum <- vec1 + vec2 # c(3, 6, 9, 12, 15)
vec_product <- vec1 * vec2 # c(2, 8, 18, 32, 50)
R follows standard mathematical precedence rules. Use parentheses to control the order of operations:
result1 <- 2 + 3 * 4 # 14 (multiplication before addition)
result2 <- (2 + 3) * 4 # 20 (parentheses change the order)
Inf
or -Inf
.is.finite()
to check for infinite results.sum()
, prod()
, and mean()
for complex calculations.Understanding arithmetic operators is crucial for data manipulation and analysis in R. They form the foundation for more complex mathematical operations and statistical computations.