Rscript ggplot - ggsave problem

2019-08-01 02:28发布

I am using the following code to draw a graph and print it to a PDF:

ggplot(agg_data_cl, aes( as.Date(date), avg_entries, color = classification ) ) +
  geom_point()

ggsave(file = "output.pdf")

This works fine when I execute the script in TextMate.

But when I call it from the commandline via RScript I get the following error:

Error in all.vars(as.formula(.$facets)) : 
  could not find function "as.formula"
Calls: print ... <Anonymous> -> <Anonymous> -> <Anonymous> -> all.vars
Execution halted

I use the following header in my RScrpipt file:

#! /usr/local/bin/Rscript --vanilla --default-packages=utils

Any ideas what could be the problem?

Here is my command line session information:

R version 2.13.1 (2011-07-08)
Platform: x86_64-apple-darwin10.8.0 (64-bit)

locale:
[1] C/UTF-8/C/C/C/C

attached base packages:
[1] grid  utils base 

other attached packages:
[1] ggplot2_0.8.9 proto_0.3-9.2 reshape_0.8.4 plyr_1.5.2   

loaded via a namespace (and not attached):
[1] grDevices_2.13.1 graphics_2.13.1  stats_2.13.1

In textmate sessionInfo() gives me more attached base packages:

attached base packages:
[1] grid      stats     graphics  grDevices utils     datasets  methods  
[8] base

I have no idea why this the case.

3条回答
叛逆
2楼-- · 2019-08-01 03:06

Two things:

1) Make sure you have library(ggplot2) _in_your_script_

2) Make sure you print() or plot() the ggplot object. (See the FAQ 7.22) This may not be the problem in this instance, since you are gg-saving, but it is a common problem with lattice or ggplot graphics from Rscript sessions.

查看更多
时光不老,我们不散
3楼-- · 2019-08-01 03:11

The problem was the --vanilla option when calling Rscript.

Here is what Rscript --help says about its options

--save              Do save workspace at the end of the session
--no-environ        Don't read the site and user environment files
--no-site-file      Don't read the site-wide Rprofile
--no-init-file      Don't read the user R profile
--restore           Do restore previously saved objects at startup
--vanilla           Combine --no-save, --no-restore, --no-site-file
                    --no-init-file and --no-environ

..and --vanilla basically means that Rscriptshould forget everything before it starts executing R commands, including some of the installed packages.

查看更多
我命由我不由天
4楼-- · 2019-08-01 03:21

as.formula is in the stats package. Not sure why it isn't being loaded, but see if manually including library(stats) at the start of your script fixes the issue.

查看更多
登录 后发表回答