gpt4 book ai didi

r - 永久替换函数

转载 作者:行者123 更新时间:2023-12-04 18:49:23 27 4
gpt4 key购买 nike

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

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

最佳答案

问题是您正在分配新版本的 layout到图形命名空间 ,这是 environment(graphics:::layout) 返回的内容.相反,您希望将分配添加到附加图形中 包裹 (即环境在您的搜索路径上显示为 "package:graphics")。

在您的示例中,查找 layout 时, R 向下搜索由 search() 返回的附加包列表,并找到原始 layoutpackage: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")

关于r - 永久替换函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8661526/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com