R:避免意外覆盖变量

big*_*377 9 namespaces r overwrite

有没有办法在你的命名空间中定义一个R中的变量,这样它就不会被覆盖(也许是一个"最终"声明)?类似下面的psuedocode:

> xvar <- 10
> xvar
[1] 10
xvar <- 6
> "Error, cannot overwrite this variable unless you remove its finality attribute"
Run Code Online (Sandbox Code Playgroud)

动机:多次运行R脚本时,有时很容易无意中覆盖变量.

Tho*_*mas 12

退房? lockBinding:

a <- 2
a
## [1] 2
lockBinding('a', .GlobalEnv)
a <- 3
## Error: cannot change value of locked binding for 'a'
Run Code Online (Sandbox Code Playgroud)

它的补充,unlockBinding:

unlockBinding('a', .GlobalEnv)
a <- 3
a
## [1] 3
Run Code Online (Sandbox Code Playgroud)


Ric*_*ton 7

您可以使用pryr包使变量保持不变.

install_github("pryr")
library(pryr)

xvar %<c-% 10
xvar
## [1] 10
xvar <- 6
## Error: cannot change value of locked binding for 'xvar'
Run Code Online (Sandbox Code Playgroud)

%<c-%运营商是一个便利的包装assign+ lockBinding.


就像巴蒂斯特在评论中所说:如果你遇到这个问题,这可能是编码风格很差的迹象.将大部分逻辑捆绑到函数中将减少变量名称冲突.