Print Output of Loop in R (Example) | Return Inside of while- & for-Loops
In this tutorial, I’ll show how to return the output of a for-loop using the print function in the R programming language.
The article contains these content blocks:
Let’s dive right in…
Example: Returning Output of for-Loop Using print() Function
In this Example, I’ll illustrate how to apply the print function to return the output of a for-loop to the RStudio console. Have a look at the following R code:
for(i in 1:5) { # Head of for-loop out <- paste0("This is my output of iteration ", i, ".") # Some output print(out) # Using print function } # [1] "This is my output of iteration 1." # [1] "This is my output of iteration 2." # [1] "This is my output of iteration 3." # [1] "This is my output of iteration 4." # [1] "This is my output of iteration 5."
As you can see, the previous R syntax returned five sentences to the RStudio console – One sentence for each iteration. Note that nothing would be shown if we wouldn’t use the print function.
We could also use the print function for other types of loops such as while-loops or repeat-loops.
Video & Further Resources
Would you like to know more about printing inside of for-loops? Then I can recommend to have a look at the following video of my YouTube channel. I’m explaining the R codes of this article in the video.
The YouTube video will be added soon.
Besides that, you might have a look at the related tutorials of my website:
Summary: This tutorial showed how to print inside of for-loops in R programming. If you have further questions on how to print a loop progress in R, let me know in the comments. Furthermore, don’t forget to subscribe to my email newsletter in order to get regular updates on new articles.