0 votes
in R Language by

For Loop in R with Examples for List and Matrix

1 Answer

0 votes
by

A for loop is very valuable when we need to iterate over a list of elements or a range of numbers. Loop can be used to iterate over a list, data frame, vector, matrix or any other object. The braces and square bracket are compulsory.

For Loop Syntax and Examples

For (i in vector) {
    Exp	
}

For Loop over a list

Looping over a list is just as easy and convenient as looping over a vector. Let's see an example

# Create a list with three vectors
fruit <- list(Basket = c('Apple', 'Orange', 'Passion fruit', 'Banana'), 
Money = c(10, 12, 15), purchase = FALSE)
for (p  in fruit) 
{ 
	print(p)
}

For Loop over a matrix

A matrix has 2-dimension, rows and columns. To iterate over a matrix, we have to define two for loop, namely one for the rows and another for the column.

# Create a matrix
mat <- matrix(data = seq(10, 20, by=1), nrow = 6, ncol =2)
# Create the loop with r and c to iterate over the matrix
for (r in 1:nrow(mat))   
    for (c in 1:ncol(mat))  
         print(paste("Row", r, "and column",c, "have values of", mat[r,c]))

Related questions

+3 votes
asked Jul 28, 2019 in R Language by Aarav2017
+3 votes
asked Jul 28, 2019 in R Language by Aarav2017
...