Print j on each iteration of the outer loop in R

For the following code: I cannot understand why j does not print on each iteration of the outer loop.

 x = 0 for (j in 1:15) { for (i in 1:100000) { x = x + 1 } print(j) } 

What R seems to do is run all of this, and print all j s at the end, and not one by one, like every time the loop repeats.

It seems that j should print after each iteration of the loop, which I don't see here?

Is there a way to make this so that j printed on each iteration of the outer loop?

thanks

+7
source share
3 answers

I assume that you are using Windows Rgui, which buffers the output of your console and then writes it in fragments (see R Windows FAQ 7.1 ). To force immediate printing to the console, you can simply add a call to flush.console() after the print() statement.

 x = 0 for (j in 1:15) { for (i in 1:100000) { x = x + 1 } print(j) flush.console() } 
+14
source
Output

R is usually buffered. You can get around this in two ways. Either (on Windows IIRC only), you can go to the R Gui menu and select Misc → Buffered Output (or press Ctrl-W) to disable buffering (which usually slows down execution), or you can call flush.console() at any the time when you want to make sure that the output is really shown (for example, to show progress).

+5
source

Not familiar with R, but this code looks right for what you are trying to do. Maybe something is related to output buffering, as I ran into the same problem in PHP where the entire script is executed before any output is displayed.

+1
source

All Articles