Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

R Basics: Operators

Introduction to Operators

Operators are special symbols in R that perform operations on variables and values. They can be classified into several categories based on their functionality. Understanding operators is essential for performing calculations and data manipulation in R.

Types of Operators

R provides various types of operators, including:

  • Arithmetic Operators
  • Relational Operators
  • Logical Operators
  • Assignment Operators
  • Bitwise Operators

1. Arithmetic Operators

Arithmetic operators are used to perform mathematical operations such as addition, subtraction, multiplication, and division. The basic arithmetic operators in R are:

  • + : Addition
  • - : Subtraction
  • * : Multiplication
  • / : Division
  • ^ : Exponentiation

Example:

result <- 5 + 3
Output: 8

2. Relational Operators

Relational operators are used to compare values. They return a boolean value (TRUE or FALSE). The relational operators in R include:

  • == : Equal to
  • != : Not equal to
  • > : Greater than
  • < : Less than
  • >= : Greater than or equal to
  • <= : Less than or equal to

Example:

is_equal <- (5 == 5)
Output: TRUE

3. Logical Operators

Logical operators are used to combine or manipulate boolean values. The main logical operators in R are:

  • && : Logical AND
  • || : Logical OR
  • ! : Logical NOT

Example:

result <- (TRUE && FALSE)
Output: FALSE

4. Assignment Operators

Assignment operators are used to assign values to variables. The primary assignment operators in R are:

  • <- : Assigns a value from right to left
  • = : Can also be used for assignment
  • >>- : Used to assign values to variables in a different environment

Example:

x <- 10
Output: x = 10

5. Bitwise Operators

Bitwise operators are used to perform bit-level operations on integers. The key bitwise operators in R are:

  • & : Bitwise AND
  • | : Bitwise OR
  • ^ : Bitwise XOR
  • << : Left shift
  • >> : Right shift

Example:

result <- 5 & 3
Output: 1

Conclusion

Operators are foundational elements in R programming that enable you to perform calculations, comparisons, and data manipulation. Understanding how to use these operators effectively will enhance your ability to write efficient and powerful R code.