永久更换功能

时间:2011-12-28 21:27:47

标签: r

有人可以解释以下代码吗?我正在用我自己的版本替换图形包中的布局功能,但它似乎重新出现了神奇

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

1 个答案:

答案 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")