[R] Runing R in a bash script

Jeffrey Horner jeff.horner at vanderbilt.edu
Tue Apr 17 23:56:16 CEST 2007

Ulrik Stervbo wrote:
 > Hello!
 > I am having issues trying to plot to a ong (or jpg)  when the R-code in a
 > bash script is executed from cron.
 > I can generate a pdf file, but when I try to write to a png, the file is
 > created, but nothing is written. If I execute the bash script from my
 > console, everything works file. Any ideas?
 > In my cron I have SHELL=/bin/bash - otherwise /bin/shell is used and the
 > folowing enery, so example is executed every minute
 > * * * * * [path]/example.sh
 > I am running
 > R version 2.4.1 (2006-12-18)
 > Here's a minimal example - two files one R-script ('example.r') and one
 > bash-script ('example.sh')
 > example.r
 > # Example R-script
 > x <- c(1:10)
 > y <- x^2
 > png(file="example2.png")
 > #pdf(file="example2.pdf")
 > plot(x,y)
 > graphics.off()
 > example.sh
 > #/bin/bash
 > #
 > # Hello world is written to exhotext every time cron executes this script
 > echo "Hello world" > echotext
 > # This works, but not when executed from cron
 > n=`R --save < example.r`
 > # using exec as in `exec R --save < example.r` dosent work with cron 
 > # This also works, but nothing is written to the png when executed 
from cron
 > R --save <<RSCRIPT
 > x <- c(1:10)
 > y <- x^2
 > png(file="example2.png")
 > #pdf(file="example2.pdf")
 > plot(x,y)
 > graphics.off()
 > #dev.off() dosent work at all when executed from cron

The png() device requires an X server for the image rendering. You might 
be able to get away with exporting the DISPLAY environment variable

export DISPLAY=:0.0 # try and connect to X server on display 0.0

within your script, but it will only work if the script is executed by 
the same user as is running the X server, *and* the X server is running 
at the time the script is executed.

There are a handful of packages that will create a png without the 
presence of an X server, and I'm partial to Cairo (since I've done some 
work on it). You can install the latest version like this:


Cairo can also outputs nice pdf's with embedded fonts... useful if you 
want to embed high-quality OpenType or TrueType fonts.



More information about the R-help mailing list