R(6), Operator

Published: by Creative Commons Licence

Types of the Operator in R

  1. arithmetic operators
  2. relational operators
  3. logical operators
  4. assignment operators
  5. Other operators

Arithmetic Operators(7)

  • + addition
  • - subtraction
  • * multiplication
  • / division
  • %% mod
  • %/% quotient
  • ^ exponentiation

examples

v <- c( 2,5.5,6)
t <- c(8, 3, 4)
print(v+t)
# 10.0  8.5  10.0

v <- c( 2,5.5,6)
t <- c(8, 3, 4)
print(v-t)
# -6.0  2.5  2.0

v <- c( 2,5.5,6)
t <- c(8, 3, 4)
print(v*t)
# 16.0 16.5 24.0

v <- c( 2,5.5,6)
t <- c(8, 3, 4)
print(v/t)
# 0.250000 1.833333 1.500000

v <- c( 2,5.5,6)
t <- c(8, 3, 4)
print(v%%t)
# [1] 2.0 2.5 2.0

v <- c( 2,5.5,6)
t <- c(8, 3, 4)
print(v%/%t)
# [1] 0 1 1

v <- c( 2,5.5,6)
t <- c(8, 3, 4)
print(v^t)
# [1]  256.000  166.375 1296.000

Relational Operators(6)

  • >
  • <
  • ==
  • <=
  • >=
  • !=

Logical Operators(5)

All the number bigger than 1 will be considered as a logical value TRUE.

&, |, !: Each elements in the 1st vector will be compared to the corresponding elements in the 2rd vector.

&&, ||: Only consider the 1st elements in vectors. And the output is a vector that contain only one element.

Assignment Operators

leftward assignment:

  • <-
  • =
  • <<-

rightward assignment:

  • ->
  • ->>

Other Operators

  • : creates a series of numbers for vectors in order.
  • %in% identifies whether the element belongs to a vector.
  • %*% multiply a matrix by its transposition.
v <- 2:8
print(v) 
# 2 3 4 5 6 7 8

v1 <- 8
v2 <- 12
t <- 1:10
print(v1 %in% t) 
print(v2 %in% t) 
# TRUE
# FALSE

M = matrix( c(2,6,5,1,10,4), nrow = 2,ncol = 3,byrow = TRUE)
t = M %*% t(M)
print(t)
#       [,1] [,2]
# [1,]   65   82
# [2,]   82  117