# Control flow and UDFs in R

#### Control Structures in R

Control structures make it possible to control the flow of a program. We frequently use these structures in our life without even knowing it for example,

if this is summer

order a cold-drink

else if this is winter

order a tea

In the same way, we can control the flow of program execution as well.Let see how do control-flow works in R

#### if-else in R

Functioning of if else structure in R is similar to the example we saw above.

Let say, we want to identify whether a given number is an even or odd number.

```
var<-5
if(var%%2>0)
print("it's an odd number") else
print("it's an even number")
```

```
## [1] "it's an odd number"
```

You can even have more than one conditions to be tested

```
var<-5
if(var%%2>0) {
print("it's an odd number")
} else if (var2%%2==0) {
print("it's an even number")
} else
print ("It's a wrong entry")
```

```
## [1] "it's an odd number"
```

#### For Loop in R

For loop repeats a piece of code for a given number.

For example, if we want to know that out of integers from 1 to 10 which are odd and which are even we can write a loop in a following way.

```
for(i in 1:10)
{
if(i%%2==0)
print("It's an odd number")
else if(i%%2>0)
print("It's an even number")
}
```

```
## [1] "It's an even number"
## [1] "It's an odd number"
## [1] "It's an even number"
## [1] "It's an odd number"
## [1] "It's an even number"
## [1] "It's an odd number"
## [1] "It's an even number"
## [1] "It's an odd number"
## [1] "It's an even number"
## [1] "It's an odd number"
```

#### While loop in R

While loop is similar to For loop but it repeats the operation until it meets a condition.

Example discussed above can be written using while loop as well.

```
i=1
while(i<11)
{
if(i%%2==0)
print("It's an odd number")
else if(i%%2>0)
print("It's an even number")
i=i+1
}
```

```
## [1] "It's an even number"
## [1] "It's an odd number"
## [1] "It's an even number"
## [1] "It's an odd number"
## [1] "It's an even number"
## [1] "It's an odd number"
## [1] "It's an even number"
## [1] "It's an odd number"
## [1] "It's an even number"
## [1] "It's an odd number"
```

Execution of while loop stopped as soon as it fulfilled the condition of 'i<11'.

What will happen if we missout the last statement in loop? – While will fall into an infinite loop as the condition 'i<11' will be satisfied forever.

#### Break and Next in R

break breaks out of a for, while or a repeat loop. When a loop encounters 'break' it breaks the iteration and passses teh control to the first statement outside the innter-most loop.

Whereas next will halt the current iteration and increase the index for next iteration.

```
for(i in 1:5)
{
for(j in 5:2)
if(i==j)
break
else
print(paste(i," combines ",j))
}
```

```
## [1] "1 combines 5"
## [1] "1 combines 4"
## [1] "1 combines 3"
## [1] "1 combines 2"
## [1] "2 combines 5"
## [1] "2 combines 4"
## [1] "2 combines 3"
## [1] "3 combines 5"
## [1] "3 combines 4"
## [1] "4 combines 5"
```

In the above example, as soon as i became equal to j it broke the loop and came out of it.

Let see an example for Next also

```
for(i in 1:10)
{
if(i%%2==0)
print(i)
else
next
}
```

```
## [1] 2
## [1] 4
## [1] 6
## [1] 8
## [1] 10
```

So, for loop written above is going throug all the integers from 1 to 10 and printing out only the even ones.

#### User Defined Functions (UDFs) in R

R offers a good amount of pre-defined functions in their base version as well through packages. But many a times we have to create our own functions with some customizations.

R functions are similar to funcstions in other programming languages. Let see a psuedo code for it-

function_name(input)

{

Do something here

return(output)

}

input refers to the argument you are passing to function, and output is something you want to get out of function.

Let's create our own function.

Objective: To write a function which will take a vector and a operation to be executed (e.g., mean, sd, sum etc.)

Inputs: Input to this function will be a vector and the operation you want to execute

Output: Output will be the value returned by operation

```
my_func<-function(vect,opr)
{
if(opr=="mean")
return(mean(vect))
else if(opr=="sd")
return(sd(vect))
else if(opr=="sum")
return(sum(vect))
else
return("select from mean, sd and sum")
}
```

In the above piece of code we have told R that calculate mean of vect if opr == “mean” and so on.

Let see what is the class of my_func and what will it print if we simply put it on console-

```
class(my_func)
```

```
## [1] "function"
```

```
my_func
```

```
## function(vect,opr)
## {
## if(opr=="mean")
## return(mean(vect))
## else if(opr=="sd")
## return(sd(vect))
## else if(opr=="sum")
## return(sum(vect))
## else
## return("select from mean, sd and sum")
## }
## <environment: 0x0000000005b62658>
```

So, printing function name on console does nothing, it just print outs the message body.

In order to get whatever we wanted out of function, we need to call it after initializing a function

```
v1<-c(1:100)
my_func(v1,"mean")
```

```
## [1] 50.5
```

```
my_func(v1,"sd")
```

```
## [1] 29.01149
```

You can even store the function output in a variable:

```
v2<-my_func(v1,"sum")
v2
```

```
## [1] 5050
```

###### Default value to a function

If your function is something which will take a particular value most frequently then it is good to pass that value as a default value to function.

Let's initialize the same function again.

```
my_func2<-function(vect,opr="mean")
{
if(opr=="mean")
return(mean(vect))
else if(opr=="sd")
return(sd(vect))
else if(opr=="sum")
return(sum(vect))
else
return("select from mean, sd and sum")
}
```

Now let's call this newly created function without passing the second argument.

```
my_func2(v1)
```

```
## [1] 50.5
```

So, if we don't pass any value to “opr” in this function call, it will take a default value i.e. “mean” in this case.

#### Returning values from a function

It is always advisable to return value from a function using “return()” but in case you don't use it, R will return the last computed value from the function

```
my_func3<-function(vect)
{
sum(vect)/2
}
my_func3(v1)
```

```
## [1] 2525
```

#### analyticsfreak

#### Latest posts by analyticsfreak (see all)

- Few interesting questions related to correlation - July 22, 2016
- How to make a reproducible example to share? - July 21, 2016
- Few random questions on Random Forest - July 20, 2016