R: Avoid random rewriting variables

Is there a way to define a variable in R in your namespace so that it cannot be overwritten (maybe ala "Final")? Something like the following psuedocode:

> xvar <- 10 > xvar [1] 10 xvar <- 6 > "Error, cannot overwrite this variable unless you remove its finality attribute" 

Motivation: When R-scripts are run multiple times, it is sometimes too easy to inadvertently rewrite variables.

+8
overwrite namespaces r
source share
2 answers

Departure ? lockBinding ? lockBinding :

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

And its complement, unlockBinding :

 unlockBinding('a', .GlobalEnv) a <- 3 a ## [1] 3 
+10
source share

You can make variables permanent using the pryr package.

 install_github("pryr") library(pryr) xvar %<c-% 10 xvar ## [1] 10 xvar <- 6 ## Error: cannot change value of locked binding for 'xvar' 

The %<c-% operator is a convenient wrapper for assign + lockBinding .


As the Baptist said in the comments: if you are having problems with this, this may be a sign of a bad coding style. Combining most of your logic into functions will reduce variable name conflicts.

+6
source share

All Articles