Download R Programming Control Flow Statements and more Study notes Programming Languages in PDF only on Docsity!
R if Statement
The if statement consists of the Boolean expressions followed by one or more statements. The if statement is the simplest decision-making statement which helps us to take a decision on the basis of the condition. The if statement is a conditional programming statement which performs the function and displays the information if it is proved true. The block of code inside the if statement will be executed only when the boolean expression evaluates to be true. If the statement evaluates false, then the code which is mentioned after the condition will run. The syntax of if statement in R is as follows:
- if (boolean_expression) {
- // If the boolean expression is true, then statement(s) will be executed.
- } Flow Chart Let see some examples to understand how if statements work and perform a certain task in R.
Example 1
- x <-24L
- y <- "shubham"
- if (is.integer(x))
- {
- print("x is an Integer")
- } Output:
Example 2
x <- 20
y<- 24
count= 0
if (x R programming treats any non-zero and non-null values as true, and if the value is either zero or null, then it treats them as false. The basic syntax of If-else statement is as follows:
if (boolean_expression) {
// statement(s) will be executed if the boolean expression is true.
} else {
// statement(s) will be executed if the boolean expression is false.
}
Example 1
local variable definition
- a<- 100
- #checking boolean condition
- if (a< 20 ){
if the condition is true then print the following
- cat("a is less than 20\n")
- } else {
if the condition is false then print the following
- cat("a is not less than 20\n")
- }
- cat("The value of a is", a) Output:
Example 2
- x <- c("Hardwork","is","the","key","of","success")
- if ("key" %in% x) {
- print("key is found")
- } else {
- print("key is not found")
- } Output:
Example 3
- a<- 100
- #checking boolean condition
- if (a< 20 ){
- cat("a is less than 20")
- if (a%% 2 == 0 ){
- cat(" and an even number\n")
- }
- else {
- cat(" but not an even number\n")
- }
- } else {
- cat("a is greater than 20")
- if (a%% 2 == 0 ){
- cat(" and an even number\n")
- }
- else {
- cat(" but not an even number\n")
- }
- } Output:
- if statement can have either zero or one else statement and it must come after any else if's statement.
- if statement can have many else if's statement and they come before the else statement.
- Once an else if statement succeeds, none of the remaining else if's or else's will be tested. The basic syntax of If-else statement is as follows:
- if (boolean_expression 1 ) {
- // This block executes when the boolean expression 1 is true.
- } else if ( boolean_expression 2 ) {
- // This block executes when the boolean expression 2 is true.
- } else if ( boolean_expression 3 ) {
- // This block executes when the boolean expression 3 is true.
- } else {
- // This block executes when none of the above condition is true.
- }
Example 1
- age <- readline(prompt="Enter age: ")
- age <- as.integer(age)
- if (age< 18 )
- print("You are child")
- else if (age> 30 )
- print("You are old guy")
- else
- print("You are adult") Output:
Example 2
- marks= 83 ;
- if (marks> 75 ){
- print("First class")
- } else if (marks> 65 ){
- print("Second class")
- } else if (marks> 55 ){
- print("Third class")
- } else {
- print("Fail")
- } Output:
R For Loop
A for loop is the most popular control flow statement. A for loop is used to iterate a vector. It is similar to the while loop. There is only one difference between for and while, i.e., in while loop, the condition is checked before the execution of the body, but in for loop condition is checked after the execution of the body. There is the following syntax of For loop in C/C++:
- for (initialization_Statement; test_Expression; update_Statement)
- {
- // statements inside the body of the loop
- }
How For loop works in C/C++?
The for loop in C and C++ is executed in the following way: o The initialization statement of for loop is executed only once. o After the initialization process, the test expression is evaluated. The for loop is terminated when the test expression is evaluated to false. o The statements inside the body of for loop are executed, and expression is updated if the test expression is evaluated to true. o The test expression is again evaluated.
o The process continues until the test expression is false. The loop terminates when the test expression is false. For loop in R Programming In R, a for loop is a way to repeat a sequence of instructions under certain conditions. It allows us to automate parts of our code which need repetition. In simple words, a for loop is a repetition control structure. It allows us to efficiently write the loop that needs to execute a certain number of time. In R, a for loop is defined as :
- It starts with the keyword for like C or C++.
- Instead of initializing and declaring a loop counter variable, we declare a variable which is of the same type as the base type of the vector, matrix, etc., followed by a colon, which is then followed by the array or matrix name.
- In the loop body, use the loop variable rather than using the indexed array element.
- There is a following syntax of for loop in R:
- for (value in vector) {
- statements
- } Example 1: We iterate all the elements of a vector and print the current value.
Create fruit vector
- fruit <- c('Apple', 'Orange',"Guava", 'Pinapple', 'Banana','Grapes')
Create the for statement
- for ( i in fruit){
- print(i)
- } Output:
- repeat {
- commands
- if(condition) {
- break
- }
- } First, we have to initialize our variables than it will enter into the Repeat loop. 1. This loop will execute the group of statements inside the loop. 2. After that, we have to use any expression inside the loop to exit. 3. It will check for the condition. It will execute a break statement to exit from the loop 4. If the condition is true. 5. The statements inside the repeat loop will be executed again if the condition is false. Example 1:
- v <- c("Hello","repeat","loop")
- cnt <- 2
- repeat {
- print(v)
- cnt <- cnt+
- if(cnt > 5) {
- break
- }
- } Output
R while loop
A while loop is a type of control flow statements which is used to iterate a block of code several numbers of times. The while loop terminates when the value of the Boolean expression will be false. In while loop, firstly the condition will be checked and then after the body of the statement will execute. In this statement, the condition will be checked n+1 time, rather than n times. The basic syntax of while loop is as follows:
- while (test_expression) {
- statement
- } Example 1:
- v <- c("Hello","while loop","example")
- cnt <- 2
- while (cnt < 7 ) {
- print(v)
- cntcnt = cnt + 1
- }} Output
Example 2
- j<- 0
- while (j< 10 ){
- if (j== 7 ){
- j=j+ 1
- next
- }
- cat("\nnumber is =",j)
- j=j+ 1
- } Output:
R Break Statement
In the R language, the break statement is used to break the execution and for an immediate exit from the loop. In nested loops, break exits from the innermost loop only and control transfer to the outer loop.
It is useful to manage and control the program execution flow. We can use it to various loops like: for, repeat, etc. There are basically two usages of break statement which are as follows:
- When the break statement is inside the loop, the loop terminates immediately and program control resumes on the next statement after the loop.
- It is also used to terminate a case in the switch statement. Note: We can also use break statement inside the else branch of if...else statement.
Syntax
There is the following syntax for creating a break statement in R
- break
Example 1: Break in repeat loop
- a <- 1
- repeat {
- print("hello");
- if (a >= 5 )
- break
- a<-a+ 1
- } Output:
- while (a < 10 ) {
- print(a)
- if (a== 5 )
- break
- a = a + 1
- } Output:
R Functions
A set of statements which are organized together to perform a specific task is known as a function. R provides a series of in-built functions, and it allows the user to create their own functions. Functions are used to perform tasks in the modular approach. Functions are used to avoid repeating the same task and to reduce complexity. To understand and maintain our code, we logically break it into smaller parts using the function. A function should be
- Written to carry out a specified task.
- May or may not have arguments
- Contain a body in which our code is written.
- May or may not return one or more output values. "An R function is created by using the keyword function." There is the following syntax of R function:
- func_name <- function(arg_1, arg_2, ...) {
- Function body
- } Components of Functions There are four components of function, which are as follows:
x
Function Name The function name is the actual name of the function. In R, the function is stored as an object with its name. Arguments In R, an argument is a placeholder. In function, arguments are optional means a function may or may not contain arguments, and these arguments can have default values also. We pass a value to the argument when a function is invoked. Function Body The function body contains a set of statements which defines what the function does. Return value It is the last expression in the function body which is to be evaluated.