Ad space (banner)
๐Ÿ“ŠR Lessons
Lesson 5 / 68

Repeating (the for loop)

This lesson covers looping in R with a for statement, with the aim of running the same work efficiently.

You can repeat using a range such as for (i in 1:5). Instead of writing the same thing over and over, a few lines express a great many repetitions — that is the power of a loop.

The sample code uses the range for (i in 1:5) to print numbered messages with cat(). The 1:5 notation, which builds a vector of consecutive integers from 1 to 5, is concise and very R-like.

A common early stumble is not realising that in R the same work can often be written with vector arithmetic and no for loop at all. Professional R code tends to favour vectorised operations (such as sapply) over for loops.

In professional work, for loops are used to handle vector elements one at a time, but replacing them with vector arithmetic where possible makes the code faster.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run R directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)