Like other languages R also has control statements; today in this post we will explore them with examples and illustrations and at the end we will also derive a function using them.
for loop:
it is to perform certain repetitive tasks for specific number of time.
example:
![](https://crackdataanalytics.com/wp-content/uploads/2021/09/image-14.png?w=485)
We have created a vector with 5 integers in it. loop variable var is passed with looplist vector; in first run of the loop var is assigned with 1 and it perform the task;
ie. 1 is assigned to task and it is printed and sleeps for 1 sec.
general syntax of for loop in R
![](https://crackdataanalytics.com/wp-content/uploads/2021/09/image-15.png?w=524)
while loop:
Like any other languages while performs the tasks until the output of the loop condition provides 1
Example:
![](https://crackdataanalytics.com/wp-content/uploads/2021/09/image-20.png?w=383)
one sample example is given below, here value of a variable i has been initialized to 0 and passed to while loop condition (i<5) the loop will proceed in first cycle when value is 0 it prints 0 and increments by 1 and when it encounters close flower bracket it returns back to check the condition. loop continues so on until it reaches value 5 that is when condition breaches and it breaks the loop
![](https://crackdataanalytics.com/wp-content/uploads/2021/09/image-19.png?w=629)
if-else statement:
if else statement is a static condition evaluation statement and based on the output of the condition it performs the tasks.
If this true then perform this task else perform that
![](https://crackdataanalytics.com/wp-content/uploads/2021/09/image-23.png?w=552)
Example:
here we have initialized variable i to 0 and passed to if condition it evaluates if i is equal to 0 then it prints the string “zero” else it prints “non-zero”
![](https://crackdataanalytics.com/wp-content/uploads/2021/09/image-21.png?w=354)
output:
![](https://crackdataanalytics.com/wp-content/uploads/2021/09/image-22.png?w=399)
using above learning here we have written a code chunk to find even and odd numbers in a vector
![](https://crackdataanalytics.com/wp-content/uploads/2021/09/image-16.png?w=791)
output of the code
![](https://crackdataanalytics.com/wp-content/uploads/2021/09/image-17.png?w=795)
we can go one step ahead and wrap everything in a function like below and call it whenever we want
![](https://crackdataanalytics.com/wp-content/uploads/2021/09/image-18.png?w=888)
that is for next post,