Kibekityo Juma Shafara
Kibekityo Juma Shafara's Blog

Follow

Kibekityo Juma Shafara's Blog

Follow
R Language Part2

Photo by Ludde Lorentz on Unsplash

R Language Part2

The Ultimate Beginner Tutorial Continues

Kibekityo Juma Shafara's photo
Kibekityo Juma Shafara
Β·Jun 12, 2022Β·

7 min read

Table of contents

  • Introduction
  • Conditional control structures
  • Loops
  • Functions

Introduction

  • In the first part of this tutorial, we looked at some basics of the R language, in this second part, we'll look at conditional control structures and functions in the R language.
  • If you missed out on the first part or you just want to remind yourself, follow this link

Conditional control structures

A program is not usually limited to a linear sequence of instructions. In many situations, a program needs to change the order of execution according to some conditions. In the R language, we use the if and if else statements to handle conditions and the consequent decisions.

if

  • As we discovered in the first part, R supports the usual logical conditions from mathematics.
  • An if statement is Written with the if keyword and is used to specify a block of code to be executed if a condition is TRUE. Example:
jumas_age <- 34
dannys_age <- 22

#check if Juma is older than danny and do something
if (jumas_age > dannys_age){
  print("Juma has more life experience")
}

# Danny, you can not do anything to me lol😁

A more general expression of an if statement is like there

if(condition){
  #statements
}

Notice the curly braces {}, R uses these to define the scope in code

Else if

In R language, we this to mean that if the previous conditions were not true, then try this other condition. Example

jumas_age <- 22
dannys_age <- 22

if (jumas_age > dannys_age){
  print("Juma has more experience")
}else if (jumas_age == dannys_age){   
  print("Juma and Danny have the same experience")
}
  • In the example above we check if Juma is older than Danny, but that is not true, so we check if they are of equal age. What do you think will be printed?

A more general else if expression is as below

if(condition1){
  #statement
}else if(condition2){
  #alternative statement
}

If Else

In R, the clause handles anything else that is not caught by the previous conditions. Below is how it works.

jumas_age <- 34
dannys_age <- 22

#check if Juma is older than danny and do something
if (jumas_age < dannys_age){
  print("Juma has more life experience")
}else if(jumas_age == dannys_age){
  print("Juma and Danny have the same experience")
}else{
  print("All in all, Danny is Junior")
}

A more general expression of the if else is as below

if(condition){
  #statement
}else{
  #alternative statement
}

Tip

You can use many conditions in one if statement using the Logical OR and logical AND, we'll see how in future

Loops

  • Other controls control structures include loops, these execute a block of code for as long as the specified condition is reached.
  • R language has only two Loops
    1. While loops
    2. for loops

1. While loop

We use while loops to execute a statement(s) as long as a condition is TRUE. Examples

counter <- 1

while (counter < 6){
  print("This is a loop")
  counter <- counter + 1
}
  • In the above example counter has a value of 1 at the start, now 1 is less than 6, so, "This is a loop" will be printed.
  • Then counter will be incremented by one, and checked if is still less than 6.
  • "This is a loop" will be printed 5 times(while counter is less than 6) because once counter is equal to 6, the condition will be failed.

A more general example of a while loop is as below

while(condition){
  #statement
}

Think about this, what would happen if counter was not incremented and stayed as 1 ? πŸ”….

Miscellaneous Operators

Before we look at the for loop, allow me to chip in miscellaneous operators(As promised in part 1). These are used to manipulate Data.

OperatorDescriptionExample
:Creates a series of numbers in a sequencex <- 1:10
%n%Find out if an element belongs to a vectorx %n% y
%*%Matrix Multiplicationx <- Matrix1 %*% Matrix2

2. for loop

In R, this loop is used to iterate over a sequence. Example 1

for (number in 1:10) {
  print(number)
}
  • In the example above, each number in the range of 1 and 10 included (1:10) will be printed.
  • For loops in R language can be used to execute a set of statements, once for each item in a vector, array, list etc.

I will discuss lists, vectors, arrays and other data structures in the third part of this tutorial. But for now, we can have a peep πŸ˜‰

Example 2

#declare and define a list of names
names <- list("shafara", "danny", "micheal", "drileba", "benja")

#print each name in the list
for (name in names){
  print(name)
}

Break

  • In R, we can stop loops before they "reach the end" by using the break statement.

While loop example

counter <- 1

while (counter < 6){
  print("This is a loop")
  counter <- counter + 1

  #break loop before counter reaches 5
  if (counter == 4){
    break
  }
}

For loop example

#declare and define a list of names
names <- list("shafara", "danny", "micheal", "drileba", "benja")

#print each name in the list
for (name in names){
  print(name)

  #break loop before it reaches drileba
  if(name == "micheal"){
    break
  }
}

Break literally kills the loop at point for a new condition you have set, like how I will stop you from walking anymore by breaking your legs if you don't respond to this hard worked easy article. Am kidding😁.

Next

  • In R loops, we can skip an iteration without stopping the loop. We use the next keyword to achieve this.

While loop example

counter <- 1

while (counter < 6){
  print("This is a loop")
  counter <- counter + 1

  #skip the value of 3
  if (counter == 3){
    break
  }
}

For loop example

#declare and define a list of names
names <- list("shafara", "danny", "micheal", "drileba", "benja")

#print each name in the list
for (name in names){
  print(name)

  #skip danny because he is young
  if(name == "danny"){
    break
  }
}

It is possible to put one loop inside another loop, this is called nesting loops, we may look at it in later parts

Functions

  • A function is a subprogram that can process data and produce (return) a value.
  • Data to be processed can be passed to the function as arguments.
  • Functions only run when they have been called.

Creating functions

To create a function in R language, use the function() keyword. Example

my_func <- function(){
  print("Hello Shafara")
}

The above function has a name my_func and prints out "Hello Shafara".

Calling a function.

  • As we discovered, functions only work if we call them, in R, calling a function is easier than you can guess.
  • We call names by using their name, followed by parenthesis, eg my_func().

Example

my_func <- function(){
  print("Hello Shafara")
}

my_func()

When I was starting to code (even sometimes now), I always forgot to call the functions and I would always curse life for introducing to coding 🀣

Arguments to Functions

  • As we discovered, data to be processed can be passed to functions as arguments.
  • Arguments are specified after the function name inside the parentheses.
  • You can add as many arguments as you want, separate them using a comma.

Example

greet <- function(name) {
  paste("Hello", name)  #paste is used to print two items together
}

#now calling the function and passing in the argument.
greet("Shafara")

The above function will print out "Hello Shafara", you can guess that, can't you?

Setting default values to function arguments.

  • By default, functions do not run if you specified that they should take in an argument and then call them without passing in the arguments.
  • To solve this error if you wish, you can set default values. These will be processed if no other value has been passed in when calling the function.

This is how you can do it.

greet <- function(name = "Juma") {
  paste("Hello", name)  #paste is used to print two items together
}

#calling the function and passing in the argument.
greet("Shafara")  #prints "Hello Shafara"

#now calling the function without an arguments
greet() #prints "Hello Juma"

Returning values

After processing data, we discovered that functions can return the value from the process. To achieve this, use return() function. Example

add <- function(number1, number2) {
  return(number1 + number2)
}

print(add(2, 3))  #prints 5

I don't want this article to go longer than this, so, this part will stop here, in the third part, we will discuss more about data structures and hopefully graphics in the R language.

Thanks if you read up to here, share and react on this article, comment about what you liked and what you think is less.

Follow me so that you do not miss out on part 3 😊.

Β 
Share this