Saturday, April 22, 2023

R Tutorial Playlist - Nested loops

 Nested loops are usual feature of almost every programming language. This feature allows you to nest one loop inside of the another.

a <- list(b=c(1,2,3), d=c(2,3,4))

for(i in a){

    for(ii in i){

        if(ii%%2==0){

            message(ii)

        }

    }

}

In this case, we have list a with two collections. With first for loop, we are iterating through collections of list a; with second for loop, we are iterating through elements of collection we are passing through with first for loop. Finally we are checking if element we are passing through is odd or even, and if it's even, we are printing it to the screen. In this way, we have utilized two for loops and one if loop in the same statement.

Check video below.



No comments:

Post a Comment