Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print j on every outside loop iteration in R

Tags:

r

For the following code: I can't figure out why j does not print on every outside loop iteration.

x = 0

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

What R seems to be doing is running the the whole thing, and at the end print out all the js, not one by one as when every loop iterates.

It seems to be that j should be printing after every loop iteration, what am I missing here?

Is there a way to make it such that j in printed on every outside loop iteration?

Thank You

like image 481
Akavall Avatar asked Dec 09 '11 19:12

Akavall


3 Answers

I'm guessing you are using the Windows Rgui, which buffers its console output, and then writes it out in chunks (see the 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()
}
like image 60
Josh O'Brien Avatar answered Nov 13 '22 12:11

Josh O'Brien


R output is typically buffered. You can circumvent this in two ways. Either (only on Windows, IIRC) you can go to the menu of the R Gui, and chose Misc -> Buffered Output (or press Ctrl-W) to disable buffering (which typically slows down execution), or you can call flush.console() any time you want to ensure that the output is actually shown (e.g. to show progress).

like image 30
Nick Sabbe Avatar answered Nov 13 '22 12:11

Nick Sabbe


Not familiar with R but that code looks right for what you are trying to do. May be something to do with output buffering as I've come accross the same issue in PHP where the whole script runs before any output is rendered.

like image 1
Ryan Tuosto Avatar answered Nov 13 '22 12:11

Ryan Tuosto