Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 666
bigO6377 Avatar asked Feb 20 '14 15:02

bigO6377


Video Answer


1 Answers

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
like image 134
Thomas Avatar answered Sep 22 '22 06:09

Thomas