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.”
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.
Copy the provided test code and run it
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
Copy the provided test code, that saves some dataframes as files, and run it
Check the resulting files in the RStudio ‘Files’ tab
Can you see the difference between paste and paste0?
Data Science and Digital Skills