Monday, August 20, 2012

R and Outputs and Printing and Loops

First off, R is really similar to python and it is making some things easier and some things more difficult.

But, R apparently won't print in loops. This is sort of weird.

So if you have...

for (i in 1:5) { summary(my_lm) }

...that won't output to the screen, but if you then just select the "summary(my_lm)" part and run that it prints fine like it should albeit once (perhaps that's a hint of sorts).

So you need...

for (i in 1:5) { print(summary(my_lm)) }

...which works like summary(my_lm) works when it's not in a loop.

Update: Apparently the same thing is true for two other conditions! One, I believe, is for outputs in general, so includes if you are trying to output to a file (or at least save to a file). So if you are trying to do something like the following generic example:

pdf("my_filename.pdf")
plot(x, y)
dev.off()


...generally, that works -- unless it's in a loop! Again, you need to do:

pdf("my_filename.pdf")
print(plot(x, y))
dev.off()


Note I am assuming you know how to do the whole pdf() or maybe there's jpg() or whatever with dev.off() at the end there.

Two, is that the output (to screen or file) call doesn't have to be in the loop itself, not exactly. It can be in a function which is called by a loop, and R notices it, so again you need to explicitly call "print()" with whatever you were trying to do that works fine when not in a loop. 

So to be clear, this does not work:

make_Plots <- function(ii) {
    # Makes the plots, saves to PDF (no it doesn't!)
    my_file <- paste("My_filename_sequence_", ii, ".pdf", sep="")
    pdf(my_file)
    plot(x, y)
    dev.off()
} # End of make_Plots 


# Main, as it were.
for (i in 1:10) {
    make_Plots(i)
}



So you see in the function call, we change the output device to be the PDF device (not the screen or anything else). So, when we call "plot" and then close the PDF device with "dev.off()" the plot call gets outputted into a PDF file with the specified name. But it doesn't, since this is an output/print call that is in a loop -- even though the loop is in the main and the output call is not!

Again, you need print(), like so:

make_Plots <- function(ii) {
    # Makes the plots, saves to PDF (this one does!)
    my_file <- paste("My_filename_sequence_", ii, ".pdf", sep="")
    pdf(my_file)
    print(plot(x, y))
    dev.off()
} # End of make_Plots 


# Main, as it were.
for (i in 1:10) {
    make_Plots(i)
}


So, I believe if you were to call the first make_Plots (no print) while control is not in a loop, it would work fine. But if you then call this otherwise fine and working and you tested it function while in a loop, it will stop working. That is insanely annoying, but I assume there is some reason for it. Sort of addressed in this FAQ, but just briefly.