Operators in R

Topic: Operators

Advertisement

Introduction

R provides various operators for performing operations on variables and values. Understanding these is fundamental to R programming.

Arithmetic Operators

# Basic arithmetic
10 + 5      # Addition: 15
10 - 5      # Subtraction: 5
10 * 5      # Multiplication: 50
10 / 5      # Division: 2
10 ^ 2      # Exponent: 100
10 %% 3     # Modulus: 1
10 %/% 3    # Integer division: 3

Comparison Operators

x <- 10
y <- 5

x == y      # Equal: FALSE
x != y      # Not equal: TRUE
x > y       # Greater than: TRUE
x < y       # Less than: FALSE
x >= y      # Greater or equal: TRUE
x <= y      # Less or equal: FALSE

Logical Operators

a <- TRUE
b <- FALSE

a & b       # AND: FALSE
a | b       # OR: TRUE
!a          # NOT: FALSE
a && b      # Short AND: FALSE
a || b      # Short OR: TRUE

Assignment Operators

# Left assignment
x <- 10
x <<- 10

# Right assignment
10 -> x
10 ->> x

# Equal assignment
x = 10

Special Operators

# Sequence operator
1:10        # 1 to 10

# Membership operator
v <- c(1, 2, 3)
2 %in% v    # TRUE

# Matrix multiplication
m1 <- matrix(1:4, 2)
m2 <- matrix(1:4, 2)
m1 %*% m2

Summary

Master these operators to perform various operations in R efficiently.

Advertisement

Advertisement

Need More Practice?

Get personalized R programming help from ChatWhole's AI-powered platform.

Get Expert Help →