rrprofile

Alias function name in .Rprofile so that it is used by all R Scripts


I am currently trying to alias the R function png with CairoPNG to generate png files. I am coming from a sys admin perspective on R - meaning I did not write any of the R code, and I am not in a position to change any of the R code. I am running it in pipelines in an elastic HPC environment. Because of the nature of the environment, I would have to install X11, cairo, etc on every single execute node at start time (which would add 2-3 minutes of arbitrary time to every job).

I have been playing around and have installed the R package Cairo which can generate png's without X11 forwarding, which is exactly what I need. If I try to use png by default:

cars <- c(1,3,5)
png("cars.png")
Error in png("cars.png") : X11 is not available

I realized I can circumvent this by assigning CairoPNG to png in an active session:

cars <- c(1,3,5)
png <- CairoPNG
png("cars.png")
plot(cars)

produces a .png file called cars.png. So I am looking to do this same thing from the .Rprofile where every R script that relies on png would actually be using CairoPNG under the hood.

In my .Rprofile, I have added:

require("Cairo")
png <- CairoPNG

When I start a new interactive R session via the command line, I can see Cairo being used, but the assignment of png <- CairoPNG is not working:

Loading required package: Cairo
> png("cars.png")
Error in png("cars.png") : X11 is not available

Any help would be greatly appreciated!


Solution

  • Add a message statement so when R starts we can verify that the .Rprofile did, in fact, run. Also use library instead of require because library will give an error right at that point if it fails making it easier to debug. Then instead of putting png in the global environment insert it into the grDevices namespace. To do that it must be unlocked first.

    # This code goes in .Rprofile file
    message("Hello")
    library("Cairo")
    unlockBinding("png", asNamespace("grDevices"))
    utils::assignInNamespace("png", CairoPNG, "grDevices")
    

    For a different approach check out:

    How to run R on a server without X11, and avoid broken dependencies