有人可以解释以下代码吗?我正在用我自己的版本替换图形包中的布局功能,但它似乎重新出现了神奇
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
答案 0 :(得分:6)
问题是您要将新版layout
分配给图形命名空间,这是environment(graphics:::layout)
返回的内容。您而不是想要分配到附加图形包(即搜索路径上显示为"package:graphics"
的环境)。
在您的示例中,在查找layout
时,R搜索search()
返回的附加包列表,并在layout
之前找到原始package:graphics
。你已经被分配到namespace:graphics
。
解决方案很简单,只需要在第一行中更改分配给env
的环境:
# 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(){}
稍微详细一点,这可能对某些人有用:
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")