The Wayback Machine - https://web.archive.org/web/20240927100135/https://www.geeksforgeeks.org/control-statements-in-r-programming/
Open In App

Control Statements in R Programming

Last Updated : 01 Jun, 2020
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Control statements are expressions used to control the execution and flow of the program based on the conditions provided in the statements. These structures are used to make a decision after assessing the variable. In this article, we’ll discuss all the control statements with the examples.

In R programming, there are 8 types of control statements as follows:

if condition

This control structure checks the expression provided in parenthesis is true or not. If true, the execution of the statements in braces {} continues. 

Syntax:

if(expression){
    statements
    ....
    ....
}

Example:




x <- 100
  
if(x > 10){
print(paste(x, "is greater than 10"))
}


Output:

[1] "100 is greater than 10"

if-else condition

It is similar to if condition but when the test expression in if condition fails, then statements in else condition are executed.

Syntax:

if(expression){
    statements
    ....
    ....
}
else{
    statements
    ....
    ....
}

Example:




x <- 5
  
# Check value is less than or greater than 10
if(x > 10){
  print(paste(x, "is greater than 10"))
}else{
  print(paste(x, "is less than 10"))
}


Output:

[1] "5 is less than 10"

for loop

It is a type of loop or sequence of statements executed repeatedly until exit condition is reached.

Syntax:

for(value in vector){
    statements
    ....
    ....
}

Example:




x <- letters[4:10]
  
for(i in x){
  print(i)
}


Output:

[1] "d"
[1] "e"
[1] "f"
[1] "g"
[1] "h"
[1] "i"
[1] "j"

Nested loops

Nested loops are similar to simple loops. Nested means loops inside loop. Moreover, nested loops are used to manipulate the matrix.

Example:




# Defining matrix
m <- matrix(2:15, 2)
  
for (r in seq(nrow(m))) {
  for (c in seq(ncol(m))) {
    print(m[r, c])
  }
}


 
Output:

[1] 2
[1] 4
[1] 6
[1] 8
[1] 10
[1] 12
[1] 14
[1] 3
[1] 5
[1] 7
[1] 9
[1] 11
[1] 13
[1] 15

while loop

while loop is another kind of loop iterated until a condition is satisfied. The testing expression is checked first before executing the body of loop.

Syntax:

while(expression){
    statement
    ....
    ....
}

Example:




x = 1
  
# Print 1 to 5
while(x <= 5){
  print(x)
  x = x + 1
}


Output:

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

repeat loop and break statement

repeat is a loop which can be iterated many number of times but there is no exit condition to come out from the loop. So, break statement is used to exit from the loop. break statement can be used in any type of loop to exit from the loop.

Syntax:

repeat { 
   statements
   ....
   .... 
   if(expression) {
      break
   }
}

Example:




x = 1
  
# Print 1 to 5
repeat{
  print(x)
  x = x + 1
  if(x > 5){
    break
   }
}


 
Output:

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

return statement

return statement is used to return the result of an executed function and returns control to the calling function.

Syntax:

return(expression)

Example:




# Checks value is either positive, negative or zero
func <- function(x){
  if(x > 0){
    return("Positive")
  }else if(x < 0){
    return("Negative")
  }else{
    return("Zero")
  }
}
  
func(1)
func(0)
func(-1)


Output:

[1] "Positive"
[1] "Zero"
[1] "Negative"

next statement

next statement is used to skip the current iteration without executing the further statements and continues the next iteration cycle without terminating the loop.

Example:




# Defining vector
x <- 1:10
  
# Print even numbers
for(i in x){
  if(i%%2 != 0){
    next #Jumps to next loop
  }
  print(i)
}


Output:

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


Previous Article
Next Article

Similar Reads

Break and Next statements in R
In R Programming Language, we require a control structure to run a block of code multiple times. Loops come in the class of the most fundamental and strong programming concepts. A loop is a control statement that allows multiple executions of a statement or a set of statements. The word ‘looping’ means cycling or iterating. Jump statements are used
3 min read
Address Errors in 'if' Statements in R
Error handling is super important when writing code, no matter which language are using even in R Programming Language. Errors can happen for all sorts of reasons, like when a user gives the computer the wrong kind of information, something happens that the user didn't expect, or the user just makes a little mistake while typing. One place where er
5 min read
Why Can't R's ifelse Statements Return Vectors?
In R, the ifelse() function is designed to perform element-wise conditional operations on vectors. However, a common point of confusion arises when trying to use ifelse() to return vectors (or lists) as elements in its output. The function's behavior and underlying design principles explain why ifelse() doesn't return vectors as expected in the R P
4 min read
What is the Relation Between R Programming and Hadoop Programming?
The relation between R programming and Hadoop revolves around integrating R with the Hadoop ecosystem to analyze large datasets that are stored in a Hadoop environment. R, primarily used for statistical analysis and data visualization, is not inherently built for handling big data. However, when combined with Hadoop, it can leverage Hadoop's distri
3 min read
Control Line Color and Type in ggplot2 Plot Legend in R
In this article, we will see how to control line color and type in ggplot2 plot legend in the R programming language. Using Default Parameters In this method, inbuilt attributes are passed to the function with appropriate values to generate the requirement. Thus, in order to change the color, col or color attribute has to be passed with the column
2 min read
Control Point Border Thickness of ggplot2 Scatterplot in R
In this article, we will see how to control Point Border Thickness of ggplot ScatterPlot in R Programming Language. For this, we will be using geom_point() function. Following is brief information about ggplot function, geom_point(). Syntax : geom_point(size, color, fill, shape, stroke) Parameter : size : Size of Pointscolor : Color of Points/Borde
2 min read
Control Size of ggplot2 Legend Items in R
In this article, we will see how to control the size of ggplot2 Legend Items in R Programming Language. To create an R plot, we use ggplot() function and for making a scatter plot geom_point() function is added to ggplot() function. Let us first create a regular plot without any modifications so that the difference is apparent. Example: C/C++ Code
2 min read
Control the Size of the Points in a Scatterplot in R
In this article, we are going to see how to control the size of the points in a scatterplot in R Programming language. We will Control the size of the points in a scatterplot using cex argument of the plot function. In this approach to control the size of the points in a scatterplot, the user needs to call the in-built function plot() and using the
2 min read
Control Point Border Thickness in ggplot2 in R
In this article, we will be looking at the approach to control point border thickness in the ggplot2 plot in the R programming language. In this method to control the point border thickness in ggplot2, the user first needs to install and import the ggplot2 package in the R console and then call the geom_point() function with the addition of the ggp
2 min read
Control the Height in fluidRow in R Shiny
The Shiny is a powerful web application framework for R that makes it easy to build interactive web applications. One of the core components of the Shiny for creating responsive layouts is the fluidRow function. However, controlling the height of the elements within the fluidRow can sometimes be challenging. This article will discuss the various me
5 min read
Getting the Modulus of the Determinant of a Matrix in R Programming - determinant() Function
determinant() function in R Language is a generic function that returns separately the modulus of the determinant, optionally on the logarithm scale, and the sign of the determinant. Syntax: determinant(x, logarithm = TRUE, ...) Parameters: x: matrix logarithm: if TRUE (default) return the logarithm of the modulus of the determinant Example 1: # R
2 min read
tidyr Package in R Programming
Packages in the R language are a collection of R functions, compiled code, and sample data. They are stored under a directory called “library” in the R environment. By default, R installs a set of packages during installation. One of the most important packages in R is the tidyr package. The sole purpose of the tidyr package is to simplify the proc
14 min read
Get Exclusive Elements between Two Objects in R Programming - setdiff() Function
setdiff() function in R Programming Language is used to find the elements which are in the first Object but not in the second Object. Syntax: setdiff(x, y) Parameters: x and y: Objects with sequence of itemsR - setdiff() Function ExampleExample 1: Apply setdiff to Numeric Vectors in R Language C/C++ Code # R program to illustrate # the use of setdi
2 min read
Add Leading Zeros to the Elements of a Vector in R Programming - Using paste0() and sprintf() Function
paste0() and sprintf() functions in R Language can also be used to add leading zeros to each element of a vector passed to it as argument. Syntax: paste0("0", vec) or sprintf("%0d", vec)Parameters: paste0: It will add zeros to vector sprintf: To format a vector(adding zeros) vec: Original vector dataReturns: Vectors by addition of leading zeros Exa
1 min read
Clustering in R Programming
Clustering in R Programming Language is an unsupervised learning technique in which the data set is partitioned into several groups called clusters based on their similarity. Several clusters of data are produced after the segmentation of data. All the objects in a cluster share common characteristics. During data mining and analysis, clustering is
6 min read
Compute Variance and Standard Deviation of a value in R Programming - var() and sd() Function
var() function in R Language computes the sample variance of a vector. It is the measure of how much value is away from the mean value. Syntax: var(x) Parameters: x : numeric vector Example 1: Computing variance of a vector # R program to illustrate # variance of vector # Create example vector x <- c(1, 2, 3, 4, 5, 6, 7) # Apply var function in
1 min read
Compute Density of the Distribution Function in R Programming - dunif() Function
dunif() function in R Language is used to provide the density of the distribution function. Syntax: dunif(x, min = 0, max = 1, log = FALSE) Parameters: x: represents vector min, max: represents lower and upper limits of the distribution log: represents logical value for probabilities Example 1: # Create vector of random deviation u <- runif(20)
1 min read
Compute Randomly Drawn F Density in R Programming - rf() Function
rf() function in R Language is used to compute random density for F Distribution. Syntax: rf(N, df1, df2) Parameters: N: Sample Size df: Degree of Freedom Example 1: # R Program to compute random values # of F Density # Setting seed for # random number generation set.seed(1000) # Set sample size N <- 20 # Calling rf() Function y <- rf(N, df1
1 min read
Data Handling in R Programming
R Programming Language is used for statistics and data analytics purposes. Importing and exporting of data is often used in all these applications of R programming. R language has the ability to read different types of files such as comma-separated values (CSV) files, text files, excel sheets and files, SPSS files, SAS files, etc. R allows its user
5 min read
Return a Matrix with Lower Triangle as TRUE values in R Programming - lower.tri() Function
lower.tri() function in R Language is used to return a matrix of logical values with lower triangle as TRUE. Syntax: lower.tri(x, diag) Parameters: x: Matrix object diag: Boolean value to include diagonal Example 1: # R program to print the # lower triangle of a matrix # Creating a matrix mat <- matrix(c(1:9), 3, 3, byrow = T) # Calling lower.tr
1 min read
Print the Value of an Object in R Programming - identity() Function
identity() function in R Language is used to print the value of the object which is passed to it as argument. Syntax: identity(x) Parameters: x: An Object Example 1: # R program to print # the value of an object # Creating a vector x <- c(1, 2, 3, 4) # Creating a list list1 <- list(letters[1:6]) # Calling the identity function identity(x) ide
1 min read
Check if Two Objects are Equal in R Programming - setequal() Function
setequal() function in R Language is used to check if two objects are equal. This function takes two objects like Vectors, dataframes, etc. as arguments and results in TRUE or FALSE, if the Objects are equal or not. Syntax: setequal(x, y) Parameters: x and y: Objects with sequence of items Example 1: # R program to illustrate # the use of setequal(
1 min read
Random Forest with Parallel Computing in R Programming
Random Forest in R Programming is basically a bagging technique. From the name we can clearly interpret that this algorithm basically creates the forest with a lot of trees. It is a supervised classification algorithm. In a general scenario, if we have a greater number of trees in a forest it gives the best aesthetic appeal to all and is counted as
4 min read
R - Object Oriented Programming
In this article, we will discuss Object-Oriented Programming (OOPs) in R Programming Language. We will discuss the S3 and S4 classes, the inheritance in these classes, and the methods provided by these classes. OOPs in R Programming Language:In R programming, OOPs in R provide classes and objects as its key tools to reduce and manage the complexity
7 min read
Check for Presence of Common Elements between Objects in R Programming - is.element() Function
is.element() function in R Language is used to check if elements of first Objects are present in second Object or not. It returns TRUE for each equal value. Syntax: is.element(x, y) Parameters: x and y: Objects with sequence of items Example 1: # R program to illustrate # the use of is.element() function # Vector 1 x1 <- c(1, 2, 3) # Vector 2 x2
1 min read
AB Testing With R Programming
Split testing is another name of A/B testing and it's a common or general methodology. It's used online when one wants to test a new feature or a product. The main agenda over here is to design an experiment that gives repeatable results and robust to make an informed decision to launch it or not. Generally, this test includes a comparison of two w
7 min read
Check if Elements of a Vector are non-empty Strings in R Programming - nzchar() Function
nzchar() function in R Language is used to test whether elements of a character vector are non-empty strings. Syntax: nzchar(x) Parameters: x: character vector Example 1: # R program to illustrate # nzchar function # Initializing a character vector x <- c("GFG", "gfg") y <- c("a", "b", "c") #
1 min read
Finding the length of string in R programming - nchar() method
nchar() method in R Programming Language is used to get the length of a character in a string object. Syntax: nchar(string) Where: String is object. Return: Returns the length of a string. R - length of string using nchar() ExampleExample 1: Find the length of the string in R In this example, we are going to see how to get the length of a string ob
2 min read
Data Reshaping in R Programming
Generally, in R Programming Language, data processing is done by taking data as input from a data frame where the data is organized into rows and columns. Data frames are mostly used since extracting data is much simpler and hence easier. But sometimes we need to reshape the format of the data frame from the one we receive. Hence, in R, we can spli
5 min read
Plotting Graphs using Two Dimensional List in R Programming
List is a type of an object in R programming. Lists can contain heterogeneous elements like strings, numeric, matrices, or even lists. A list is a generic vector containing other objects. Two-dimensional list can be created in R programming by creating more lists in a list or simply, we can say nested lists. The list() function in R programming is
2 min read
Article Tags :