gpt4 book ai didi

r - '<<-' 分配没有可见绑定(bind)

转载 作者:行者123 更新时间:2023-12-03 09:22:48 25 4
gpt4 key购买 nike

我已经解决了人们在检查包裹时收到的“无可见绑定(bind)”注释的变体。但是,当应用于“<<-”赋值时,我无法解决这种情况。

具体来说,我在多个函数中定义并使用了局部变量,例如:

fName = function(df){
eval({vName<<-0}, envir=environment(fName))
}

但是,当我从 devtools 运行 check() 时,出现错误:

fName: no visible binding for '<<-' assignment to 'vName'

因此,我尝试使用不同的语法,如下所示:

fName = function(df){
assign("vName",0, envir=environment(fName))
}

但是得到了 check() 错误:

cannot add bindings to a locked environment

当我尝试时:

fName = function(df){
assign("vName",0, envir=environment(-1))
}

我收到错误:

use of NULL environment is defunct

所以,我的问题是如何完成赋值运算符 <<- 而无需在 devtools 的 check() 中获得注释。

谢谢。

最佳答案

简单的答案是 - 不要使用 <<-在你的包裹里。分配环境的一种替代方法(但不是有意义的方法)是创建锁定绑定(bind)。

e <- new.env()
e$vName <- 0L
lockBinding("vName", e)
vName
# Error: object 'vName' not found
with(e, vName)
# [1] 0
e$vName <- 5
# Error in e$vName <- 5 : cannot change value of locked binding for 'vName'

您还可以锁定环境,但不能锁定有意义的环境。

lockEnvironment(e)
rm(vName, envir = e)
# Error in rm(vName, envir = e) :
# cannot remove bindings from a locked environment

看看help(bindenv) ,这是一本好书。

已更新 由于您提到您可能正在等待分配而不是在加载时,请阅读 help(globalVariables)这是另一本畅销书 ?

For globalVariables, the names supplied are of functions or other objects that should be regarded as defined globally when the check tool is applied to this package. The call to globalVariables will be included in the package's source. Repeated calls in the same package accumulate the names of the global variables.

关于r - '<<-' 分配没有可见绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28312408/

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