Introduction
In this chapter, you will learn about arithmetic operators in R. Arithmetic operators are used to perform basic mathematical operations on numeric values. These operations include addition, subtraction, multiplication, division, modulus, and exponentiation. Understanding how to use these operators is essential for performing calculations and data analysis in R.
Arithmetic Operators in R
1. Addition (+
)
The addition operator adds two numeric values.
Example:
# Addition
a <- 10
b <- 5
sum <- a + b
print(sum) # Output: 15
2. Subtraction (-
)
The subtraction operator subtracts one numeric value from another.
Example:
# Subtraction
a <- 10
b <- 5
difference <- a - b
print(difference) # Output: 5
3. Multiplication (*
)
The multiplication operator multiplies two numeric values.
Example:
# Multiplication
a <- 10
b <- 5
product <- a * b
print(product) # Output: 50
4. Division (/
)
The division operator divides one numeric value by another.
Example:
# Division
a <- 10
b <- 5
quotient <- a / b
print(quotient) # Output: 2
5. Modulus (%%
)
The modulus operator returns the remainder of the division of one numeric value by another.
Example:
# Modulus
a <- 10
b <- 3
remainder <- a %% b
print(remainder) # Output: 1
6. Exponentiation (^
)
The exponentiation operator raises one numeric value to the power of another.
Example:
# Exponentiation
a <- 2
b <- 3
power <- a ^ b
print(power) # Output: 8
Example Program with Arithmetic Operators
Here is an example program that demonstrates the use of arithmetic operators in R:
# R Program to Demonstrate Arithmetic Operators
# Declare variables
a <- 12
b <- 4
# Perform arithmetic operations
sum <- a + b # Addition
difference <- a - b # Subtraction
product <- a * b # Multiplication
quotient <- a / b # Division
remainder <- a %% b # Modulus
power <- a ^ b # Exponentiation
# Print results
print(paste("Sum:", sum)) # Output: Sum: 16
print(paste("Difference:", difference)) # Output: Difference: 8
print(paste("Product:", product)) # Output: Product: 48
print(paste("Quotient:", quotient)) # Output: Quotient: 3
print(paste("Remainder:", remainder)) # Output: Remainder: 0
print(paste("Power:", power)) # Output: Power: 20736
Conclusion
In this chapter, you learned about arithmetic operators in R, including addition, subtraction, multiplication, division, modulus, and exponentiation. These operators are fundamental for performing mathematical calculations and data analysis in R. By mastering these operators, you can perform a wide range of numerical operations and enhance your data analysis capabilities.