R Operators

Arithmetic operators

These operators are used to carry out mathematical operations like addition and multiplication.

Operator Description
+ Addition
- Subtraction
__*__ Multiplication
/ Division
^ Exponent
%% Modulus
%/% Integer Division
x <- 50
y <- 5
z <- 3

# addition operator
x + y
## [1] 55
# subtraction operator
x - y
## [1] 45
# Multiplication
x * y
## [1] 250
# Division operator
x / y
## [1] 10
# power operator
y ^ z
## [1] 125
# Modulus Operator
x %% y
## [1] 0
x %% z
## [1] 2
# Integer Division

x / z
## [1] 16.66667
x %/% z
## [1] 16

Assignment operators

Assignment operators are used to assign values to variables

There are two kinds of assignment operators: - Left <- and =

  • Right ->
# left assignment
my_var <- 3
print(my_var)
## [1] 3
# right assignment

3 -> y
print(y)
## [1] 3
2*3 -> x
print(x)
## [1] 6

Logical operators

Logical operators are used to combine conditional statements

Logical operators are used to carry out Boolean operations like AND, OR

Operator Description
! Logical Not
& Element-wise Logical AND operator. It returns TRUE if both elements are TRUE
&& Logical AND operator
| Elementwise- Logical OR operator.
|| Logical OR operator.

Zero is considered FALSE and non-zero numbers are taken as TRUE

x <- c(TRUE,FALSE,0,6)
y <- c(FALSE,TRUE,FALSE,TRUE)

!x
## [1] FALSE  TRUE  TRUE FALSE
x&y
## [1] FALSE FALSE FALSE  TRUE
x&&y
## [1] FALSE
x|y
## [1]  TRUE  TRUE FALSE  TRUE
x||y
## [1] TRUE

Comparison operators

Comparison operators are used to compare two values

These conditions can be used in several ways, most commonly in if statements and loops.

Operator Description
< Less than
> Greater than
<= Less than or Equal to
>= Greater than or Equal to
== Equal to
!= Not Equal to
x <- 50
y <- 5
z <- 3

# less than
y < x
## [1] TRUE
# greater than
x > x
## [1] FALSE
# less than or equal to
x <= y
## [1] FALSE
# greater than or equal to
5 >= 5
## [1] TRUE
# equal to
5 == 5
## [1] TRUE
# not equal to
5 != 5
## [1] FALSE
# operations on vectors

x <- c(2,8,3)
y <- c(6,4,1)

x > y
## [1] FALSE  TRUE  TRUE

Miscellaneous Operators

Miscellaneous operators are used to manipulate data

Operator Description
: Creates a series of numbers in a sequence
%in% Find out if an element belongs to a vector
%*% Matrix Multiplication
# the : operator
print(10:15)
## [1] 10 11 12 13 14 15
# the %in% operator
fruits <- c("banana","orange","apple","mango")

"passion" %in% fruits
## [1] FALSE
"banana" %in% fruits
## [1] TRUE

Matrix multiplication

The inverse of matrix is another matrix, which on multiplication with the given matrix gives the multiplicative identity.

matrix1 <- matrix(c(1,0,-1,2),nrow=2,ncol=2)
matrix2 <- matrix(c(1,0,0.5,0.5),nrow=2,ncol=2)

matrix1
##      [,1] [,2]
## [1,]    1   -1
## [2,]    0    2
matrix2
##      [,1] [,2]
## [1,]    1  0.5
## [2,]    0  0.5
matrix1 %*% matrix2
##      [,1] [,2]
## [1,]    1    0
## [2,]    0    1

Conditions and If Statements

if statement

An “if statement” is written with the if keyword, and it is used to specify a block of code to be executed if a condition is TRUE

The if statement takes a condition; if the condition evaluates to TRUE, the R code associated with the if statement is executed.

Syntax

if(condition){
  expression
}

The condition to check appears inside parentheses, while the R code that has to be executed if the condition is TRUE, follows in curly brackets ( expression).

R uses curly brackets { } to define the scope in the code.

a <- 33
b <- 200

if (b > a) {
  print("b is greater than a")
}
## [1] "b is greater than a"

if ... else statement

The else keyword catches anything which isn’t caught by the preceding conditions

The else statement does not need an explicit condition; instead, it has to be used with an if statement.

The code associated with the else statement gets executed whenever the condition of the if condition is not TRUE.

Syntax

if (condition) {
  expr1
} else {
  expr2
}
x <- 15
y <- 2

if(x%%y==0){
  print("x is divisible by y")
}else {
  print("x is not divisible by y")
}
## [1] "x is not divisible by y"

if ... else if... else statement

The else if keyword is R’s way of saying “if the previous conditions were not true, then try this condition”

if (condition1) {
  expr1
} else if (condition2) {
  expr2
} else {
  expr3
}
x <- 90
y <- 95
# x <- y
z <- 10
w <- 5

if(x%%z==0){
  print("x is divisible by 10")
} else if(x%%w==0){
  print("x is divisible by 5")
}else{
  "x is not divisible by both 5 and 10"
}
## [1] "x is divisible by 10"

Loops

For Loop

A for loop is used for iterating over a sequence.

For loop in R Programming Language is useful to iterate over the elements of a list, dataframe, vector, matrix, or any other object.

Syntax

for(item in vector){
  # code block
}

With the for loop we can execute a set of statements, once for each item in a vector, array, list, dataframe.

# loop over a range
for(i in 1:10){
  print(i^2)
}
## [1] 1
## [1] 4
## [1] 9
## [1] 16
## [1] 25
## [1] 36
## [1] 49
## [1] 64
## [1] 81
## [1] 100
# loop over a vector

capitals <- c("Beijing","New Delhi","Brasil","Washington DC","Addis Ababa","Cairo")

for(capital in capitals){
  print(capital)
}
## [1] "Beijing"
## [1] "New Delhi"
## [1] "Brasil"
## [1] "Washington DC"
## [1] "Addis Ababa"
## [1] "Cairo"
# loop over two vectors
countries <- c("China","India","Brazil","USA","Ethiopia","Egypt")

combo <- list(countries,capitals)

# lets use an index approach
for(idx in 1:length(combo)){
  # use [[]] to index as vector
  # print(combo[[idx]])
  for(sub_idx in 1:length(combo[[idx]])){
    print(combo[[idx]][sub_idx])
  }
}
## [1] "China"
## [1] "India"
## [1] "Brazil"
## [1] "USA"
## [1] "Ethiopia"
## [1] "Egypt"
## [1] "Beijing"
## [1] "New Delhi"
## [1] "Brasil"
## [1] "Washington DC"
## [1] "Addis Ababa"
## [1] "Cairo"

Fizz Buzz Challenge

Write a program that checks if a number is a multiple of three, five and both three and five.

For multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.

# iterate over a sequence

for(x in 1:15){
  # first check if x (number in current iteration) is divisible by both 3 and 5
  if(x%%3==0 && x%%5==0){
    print("FizzBuzz")
  }else if(x%%3==0){
    # if the number is not divisible by both 3 and 5, check if it is divisible by 3
    print("Fizz")
  }else if(x%%5==0){
    # if the number is not divisible by both 3 and 5, and not divisible by 3, check if it is divisible by 5
    print("Buzz")
  }else{
    # if none of the above conditions are met, print the number
    print(x)
  }
}
## [1] 1
## [1] 2
## [1] "Fizz"
## [1] 4
## [1] "Buzz"
## [1] "Fizz"
## [1] 7
## [1] 8
## [1] "Fizz"
## [1] "Buzz"
## [1] 11
## [1] "Fizz"
## [1] 13
## [1] 14
## [1] "FizzBuzz"

While Loop

With the while loop we can execute a set of statements as long as a condition is TRUE

# initialize loop index
i = 10

while(i>0){
  print(i)
  # decrement loop index
  i = i - 1
}
## [1] 10
## [1] 9
## [1] 8
## [1] 7
## [1] 6
## [1] 5
## [1] 4
## [1] 3
## [1] 2
## [1] 1

Counting Factorials using while loop

n <- 5

# initialize product variable
factorial = 1
while(n>0){
  factorial <- factorial * n
  # decrement n by factor of 1
  n <- n-1
}

factorial
## [1] 120

Repeat Loop

It is a simple loop that will run the same statement or a group of statements repeatedly until the stop condition has been encountered. Repeat loop does not have any condition to terminate the loop, a programmer must specifically place a condition within the loop’s body and use the declaration of a break statement to terminate this loop. If no condition is present in the body of the repeat loop then it will iterate infinitely.

Syntax

repeat 
{ 
   statement
 
   if( condition ) 
   {
      break
   }
}

Example: Factorial of n using repeat loop

factorial <- 1

n <- 5

repeat{
  factorial <- factorial * n
  n <- n - 1
  if(n==1){
    break;
  }
}

factorial
## [1] 120

break and next in R loops

break

With the break statement, we can stop the loop before it has looped through all the items

fruits <- c("Mango","Banana","Apple",
            "Plum","Peach","Straw Berry",
            "Coconut","Guava","Orange")

# initialize index
idx <- 1

for(fruit in fruits) {
  # suppose we are looking for a Straw Berry
  
  var <- paste(idx, fruit)
  print(var)
  
  # once we find the Straw Berry we can exit the loop
  if (fruit == "Straw Berry") {
    break
  }
  
  idx <- idx + 1
}
## [1] "1 Mango"
## [1] "2 Banana"
## [1] "3 Apple"
## [1] "4 Plum"
## [1] "5 Peach"
## [1] "6 Straw Berry"
print("loop over")
## [1] "loop over"

Functions

Functions enable you to create reusable blocks of code. They create modularity (separate code blocks that perform specific functions) in your code and enable your code to stay organized.

Functions facilitate code reusability. In simple terms, when you want to do something repeatedly, you can define that something as a function and call that function whenever you need to.

A function is a block of code which only runs when it is called.

You can pass data, known as arguments, into a function.

Syntax

my_function <- function(<arguments>){    
    #do something
 }

A function is declared with function() directive.

# define a function
greeting <- function(name,city){
  greet <- paste("Hello",name)
  ask <- paste("How is ",city,"?",sep="")
  print(greet)
  print(ask)
  
  # output in one line
  # cat(greet,ask,sep=".")
}

# call the function 
greeting("John Dawa","Nakuru")
## [1] "Hello John Dawa"
## [1] "How is Nakuru?"

Return value of the function is the last expression to be evaluated in the function body. You don’t need to specifically write a return statement.

net_salary <- function(gross_salary,tax){
  net <- gross_salary - tax
}

intern <- net_salary(20000,5000)
supervisor <- net_salary(70000,15000)

paste("Intern Salary After Tax", intern)
## [1] "Intern Salary After Tax 15000"
paste("Supervisor Salary After Tax", supervisor)
## [1] "Supervisor Salary After Tax 55000"

Default values of arguments

greetings <- function(name,country="Kenya",city="Nairobi"){
  stmt1 <- paste("Hello, ",name,end=".",sep="")
  stmt2 <- paste("How is",city,country,"?")
  cat(stmt1,stmt2)
}

greetings("Jane")
## Hello, Jane. How is Nairobi Kenya ?

Matching Argument Values

R arguments can be matched positionally or by their names. That is if you don’t specify their names, you need to place arguments in the order mentioned during function definition. Otherwise, you can use the argument names and can place them in any order.

# match positionally
greetings("Jane","Cairo","Egypt")
## Hello, Jane. How is Egypt Cairo ?
print("")
## [1] ""
# match by argument name
greetings("Jane",city = "Cairo",country = "Egypt")
## Hello, Jane. How is Cairo Egypt ?

How to know about arguments of a function

The args() inbuilt function displays the argument names and corresponding default values of a function

# retrieve the argument names of a function
args(function_name)
# let's see what arguments the args function takes 
# also returns the default values if specified
args(args)
## function (name) 
## NULL
greetings <- function(name,country="Kenya",city="Nairobi"){
  stmt1 <- paste("Hello, ",name,end=".",sep="")
  stmt2 <- paste("How is",city,country,"?")
  cat(stmt1,stmt2)
}

greetings("Jane")
## Hello, Jane. How is Nairobi Kenya ?
args(greetings)
## function (name, country = "Kenya", city = "Nairobi") 
## NULL

Challenges

  1. Write an R function that accepts a vector and calculate the product of the elements
my_func <- function(lst){
  # initialize product variable
  prod = 1
  for(num in lst){
    prod = prod * num
  }
  return(prod)
}

my_func(1:5)
## [1] 120
  1. Write an R function that accepts a number and calculates the factorial of of the given number

Example:

Sample Input: 5

Sample Output: 120

# your solution here
factorial <- function(x){
  # code here
}

factorial(5)
## NULL
#

References