bigO6377
bigO6377

Reputation: 1274

R: Avoid accidently overwriting variables

Is there any way to define a variable in R in your namespace, such that it can't be overwritten (maybe ala a "Final" declaration)? 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 running R scripts multiple times, it's sometimes too easy to inadvertently overwrite variables.

Upvotes: 11

Views: 2374

Answers (2)

Richie Cotton
Richie Cotton

Reputation: 121077

You can make variables constant 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 convenience wrapper for assign + lockBinding.


Like Baptiste said in the comments: if you are having problems with this, it's a possible sign of poor coding style. Bundling the majority of your logic into functions will reduce variable name clashes.

Upvotes: 7

Thomas
Thomas

Reputation: 44535

Check out ? 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

Upvotes: 12

Related Questions