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
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With