Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Permanently replacing a function

Tags:

r

Could someone explain the following code? I'm replacing the layout function in the graphics package with my own version, but it seems to re-appear magically

env = environment( graphics:::layout )
unlockBinding( "layout" , env = env )
assign( "layout" , function(){} , envir = env )
lockBinding( "layout" , env = env )

# this still shows the original layout function!  how is that possible?
layout

# this shows function(){} as expected
graphics:::layout
like image 719
SFun28 Avatar asked Dec 28 '11 21:12

SFun28


1 Answers

The problem is that you are assigning your new version of layout to the graphics namespace, which is what is returned by environment(graphics:::layout). You instead want to make the assignment into the attached graphics package (i.e. the environment appearing as "package:graphics" on your search path).

In your example, when looking for layout, R searches down the list of attached packages returned by search(), and finds the original layout in package:graphics, before it ever gets to function you've assigned into namespace:graphics.

The solution is simple, requiring only a change of environment assigned to env in the first line:

# Assign into <environment: package:graphics>
# rather than <environment: namespace:graphics>
env <- as.environment("package:graphics")

unlockBinding( "layout" , env = env )
assign( "layout" , function(){} , envir = env )
lockBinding( "layout" , env = env )

# Now it works as expected
layout
# function(){}

A bit more elaboration, that may be useful to some:

search()    # Shows the path along which symbols typed at the command 
            # will be searched for. The one named "package:graphics" 
            # is where 'layout' will be found.

# None of these return the environment corresponding to "package graphics"
environment(layout)
environment(graphics::layout)
environment(graphics:::layout)

# This does
as.environment("package:graphics")
like image 179
Josh O'Brien Avatar answered Sep 23 '22 22:09

Josh O'Brien