0

I tried to pass a number on a command line to a very simple R script to do some plotting.

I got this plot.r file:

args<-commandArgs(TRUE)

vmcn<-as.integer(args[1])

library(ggplot2)
library(grid)

file<-read.table("my file.txt",header=F)

ggplot(file,aes(x=V1))+geom_histogram(binwidth=1,aes(y=..count../vmcn*100))+theme_bw()

ggsave(filename="myfile.pdf",width=4,height=4)

When I run it this way:

Rscript plot.r 5000

I got the error:

Error in eval(expr, envir, enclos) : object 'vmcn' not found
Calls: print ... <Anonymous> -> as.data.frame -> lapply -> FUN -> eval
Execution halted

Can someone enlighten me on what's wrong?

olala
  • 4,146
  • 9
  • 34
  • 44

1 Answers1

4

This actually has nothing to do with the fact that you run R via command line. Your script also doesn't work interactively. This is to do with the way the aes function of ggplot2 searches for your objects. Rather surprisingly, it does not by default search in the global environment. Here's how you fix it:

# some reproducible data 
set.seed(1)
vmcn <- 100
file <- data.frame(V1 = rnorm(1000))
# and the fixed plotting command 
ggplot(file, aes(x=V1)) +
  geom_histogram(binwidth=1, aes(y=..count..*100/get("vmcn", envir=.GlobalEnv))) +
  theme_bw()
shadow
  • 21,823
  • 4
  • 63
  • 77
  • it worked! thanks for the answer, i learned something about R again. – olala Jul 30 '14 at 15:54
  • 1
    I ran into [this problem before](http://stackoverflow.com/questions/24538031/how-can-i-make-a-frequency-distribution-bar-plot-in-ggplot2/24541345#24541345) as well. It seems to only happen with aesthetics where you use the special `..var..` variables. – MrFlick Jul 30 '14 at 16:42