R Constructs

Constructs

Sometimes there is a need to produce output as per our decisions and also we might like to control the flow of the code.

So, R has decision making constructs like if, if else, switch and also constructs for controlling the iterations like while, repeat and for

Decision making structures require the programmer to specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed, if the condition is determined to be True or False.

Decision making structures in r language
CODE/PROGRAM/EXAMPLE
#IF

	if(is.integer(a)) {
	   print("The value is an Integer")
	}

	#IF ELSE

	if(is.integer(a)) {
	   print("The value is an Integer")
	}
	else {
	   print("Please enter the correct value")
	}

	#SWITCH

	x <- "red"
	switch(x, "red" = "#FF0000", "blue" = "#4169E1")

Control Flow Constructs

The ‘while’ loop executes the same code again and again until a stop condition is met

Syntax
Syntax:
	  while (test_expression) {

				statement
			}
	  
	  #While Loop

		a <- 5
		while(a < 10) {
			  print("I am while loop")
			  a = a + 1
		}

The ’repeat’ loop executes the same code again and again until a stop condition is met

Syntax
Syntax:

		 repeat { 

			code

			if(condition){ break }

		 }

		#Repeat Loop

		x <- 0
		repeat {
			 if(x >= 5) {break}
			 print("Hi Everyone")
			 x <- x + 1
		}

Control Flow Constructs

A ‘for’ loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times

Syntax
#Syntax: 

	   for (value in vector) {

		statements

	   }
Control Flow Constructs in r language
CODE/PROGRAM/EXAMPLE
#For Loop

	for(i in 1:10) {
		print("Hi, i am for loop")
	}

Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed

Notepad

Note : break() function terminate the loop statement

#Constructs_in_r_programming #if_function_in_r_language #if_else_function_in_r_language #switch_function_in_r_language #for_loop_in_r_language

(New page will open, for Comment)

Not yet commented...