From murdoch.duncan at gmail.com  Mon Aug  8 14:19:30 2011
From: murdoch.duncan at gmail.com (Duncan Murdoch)
Date: Mon, 08 Aug 2011 08:19:30 -0400
Subject: [Rd] Overwriting imported function in another package
In-Reply-To: <CABFfbXvuYi=nYQ72ULVyQX87q288Wu7jAioPMXmBhKU6EvcJ+g@mail.gmail.com>
References: <CABFfbXvuYi=nYQ72ULVyQX87q288Wu7jAioPMXmBhKU6EvcJ+g@mail.gmail.com>
Message-ID: <4E3FD452.8070209@gmail.com>

On 08/08/2011 7:02 AM, Jeroen Ooms wrote:
> I am running into a limitation of the grid::grid.newpage function, for
> which I would like to overwrite this function with a slightly modified
> one. Hopefully this is a temporary working solution until the package
> gets updated. I found a way to overwrite the function in the
> package:grid namespace. However, lattice imports grid rather than
> depending on it. So I need a way to overwrite this imported version as
> well. The code below shows the fix which works for ggplot (because it
> depends on grid), but it doesn't work for lattice, because it imports
> grid. Is there any way to overwrite grid.newpage for all
> instantiations of it?

Yes, modify the source and recompile R.

Duncan Murdoch

> #packages
> library(grid);
> library(lattice);
> library(ggplot2);
>
> #create the modified function.
> hookfun<- deparse(body(plot.new))[1:6]
> oldfun<- deparse(body(grid::grid.newpage))[-1];
> newfun<- grid::grid.newpage;
> body(newfun)<- parse(text=c(hookfun, oldfun));
>
> #overwrite it in the package
> unlockBinding("grid.newpage", as.environment("package:grid"))
> assign("grid.newpage", newfun, pos="package:grid")
>
> #this seems ok:
> get('grid.newpage', as.environment("package:grid"));
> get('grid.newpage', as.environment("package:lattice"));
>
> #but this is still the old one
> get('grid.newpage', environment(histogram));
>
> #test if it worked:
> setHook("before.plot.new", function() {message("Yay! A new plot.");});
> qplot(rnorm(100)); #it worked for ggplot2
> histogram(rnorm(100)); #didn't work for lattice
>
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel



[Rd] Overwriting imported function in another package
Duncan Murdoch