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:
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
while loop:
Like any other languages while performs the tasks until the output of the loop condition provides 1
Example:
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
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
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”
output:
using above learning here we have written a code chunk to find even and odd numbers in a vector
output of the code
we can go one step ahead and wrap everything in a function like below and call it whenever we want
that is for next post,