The solution is to explicitly call print()
on ggplot object:
library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg))
p <- p + geom_point()
print(p)
ggplot
function returns object of class ggplot; ggplot2 works by overloading print
function to behave differently on objects of class ggplot - instead of printing them to STDOUT, it creates chart.
Everything is working well in interactive mode, because R assumes that most of commands are run through print()
function. This is for our convenience and allows us to type rnorm(1)
and get any visible output. When Run current selection command is used (Ctrl+Enter
), RStudio behaves as if each selected line was typed in interactive mode and run. You can verify that by checking your command history in Console
pane after running few selected lines.
But this convenient mode is abandoned when file is read by source()
. Since this function is intended to run (potentially long and computationally-expensive) R scripts, it is undesirable to pollute STDOUT with low-priority messages. That's why source()
by default will output only error message. If you want anything else, you have to explicitly ask for that.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…