For Loops

DRS Training

R For Loops

Loops are a useful part of many programming languages but are perhaps used in more limited ways in R due to the extensive use of “Vectorization”.

“Most of R’s functions are vectorized, meaning that the function will operate on all elements of a vector without needing to loop through and act on each element one at a time. This makes writing code more concise, easy to read, and less error prone.”

Vectorization approaches are also used extensively within dataframes.

The general structure of a for loop is:


The sequence is a vector/list and val takes on each of element of the sequence in turn during the loop. In each iteration, the main code is evaluated in conjunction with that value.


Task 1

Copy the provided test code and run it

Task 2

Try a vectorised alternative


You can investigate the commands/functions cat and paste further using R help e.g: ?cat


But some tasks do lend themselves to for loops, in particular reading things from or writing things to files

Task 3

Copy the provided test code, that saves some dataframes as files, and run it

Task 4

Check the resulting files in the RStudio ‘Files’ tab

Can you see the difference between paste and paste0?