Creating Multiple Plots within for-Loop in R

R




# create a matrix of data
mat <- matrix(rnorm(100), ncol = 5)
 
# set up the plot layout
par(mfrow = c(2, 3))
 
# loop over columns of the matrix
for (i in 1:5) {
  # create a histogram for each column
  hist(mat[, i], main = paste("Column", i), xlab = "Values", col = "lightblue")
}


Output:

For loop in R

In this example, the for loop iterates over the columns of the matrix mat, and for each column, a histogram of the values is created using the hist() function. The main argument of the hist() function is used to set the title of each plot, and the xlab argument is used to label the x-axis. The col argument is used to set the color of the bars in the histogram to light blue.

The par() function is used to set up the plot layout with mfrow = c(2, 3), which specifies that the plots should be arranged in 2 rows and 3 columns. This means that the for loop will create 5 plots, each of which is a histogram of one of the columns of the matrix mat, arranged in a 2×3 grid.

Here as soon as zero is encountered, that iteration is discontinued and the condition is checked again. Since 21 is not equal to 0, it is printed. As we can conclude from the above two programs the basic difference between the two jump statements is that the break statement terminates the loop and the next statement skips a particular iteration of the loop.



For loop in R

For loop in R Programming Language is useful to iterate over the elements of a list, data frame, vector, matrix, or any other object. It means the for loop can be used to execute a group of statements repeatedly depending upon the number of elements in the object. It is an entry-controlled loop, in this loop, the test condition is tested first, then the body of the loop is executed, the loop body would not be executed if the test condition is false.

Similar Reads

For loop in R Syntax:

for (var in vector) { statement(s) }...

Flowchart of For loop in R:

For loop in R...

Nested For-loop in R

...

Jump Statements in R

...

Creating Multiple Plots within for-Loop in R

...

Contact Us