Code works in Rstudio but not in console

I have a very simple code that appears to work perfectly in RStudio but does nothing if I source the script from within R:
If I save the following as test.R

png(file = paste(format(Sys.time(), "%Y-%m-%d"
                 sep = ""
ggplot(data = mtcars) +
  geom_point(aes(x = drat, y = wt)

I see the png saved in my working directory if source the above script via RStudio. But if I open R from the command line, and source the same script my plot doesn't get saved. Is there a reason for this? (I checked I have the right working directory via getwd()).

Does R from the command line save to some other location? Or is there something else going on?

CLI R will save to the directory in which it is open by default.

I thought that at first, but

  1. when I check with getwd() its the same directory; I am pretty sure CLI won't save in any parent node
  2. also, if I use write_csv, CLI R writes the csv to the correct directory.

I think I figured it out: looking at the FAQ

The most likely reason is that you forgot to tell R to display the graph. Lattice functions such as xyplot() create a graph object, but do not display it (the same is true of ggplot2 graphics, and Trellis graphics in S-PLUS). The print() method for the graph object produces the actual display. When you use these functions interactively at the command line, the result is automatically printed, but in source() or inside your own functions you will need an explicit print() statement.

Since I used ggplot(), I needed an explicit print statement to save upon sourcing.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.