Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring a Const Variable in R

I'm working in R, and I'd like to define some variables that I (or one of my collaborators) cannot change. In C++ I'd do this:

const std::string path( "/projects/current" ); 

How do I do this in the R programming language?

Edit for clarity: I know that I can define strings like this in R:

path = "/projects/current" 

What I really want is a language construct that guarantees that nobody can ever change the value associated with the variable named "path."

Edit to respond to comments:

It's technically true that const is a compile-time guarantee, but it would be valid in my mind that the R interpreter would throw stop execution with an error message. For example, look what happens when you try to assign values to a numeric constant:

> 7 = 3 Error in 7 = 3 : invalid (do_set) left-hand side to assignment 

So what I really want is a language feature that allows you to assign values once and only once, and there should be some kind of error when you try to assign a new value to a variabled declared as const. I don't care if the error occurs at run-time, especially if there's no compilation phase. This might not technically be const by the Wikipedia definition, but it's very close. It also looks like this is not possible in the R programming language.

like image 338
James Thompson Avatar asked Jun 01 '09 20:06

James Thompson


People also ask

How do you declare variables with const?

Variables can be declared as constants by using the “const” keyword before the datatype of the variable. The constant variables can be initialized once only. The default value of constant variables are zero.

How do I declare a variable in R?

Rules for R variables are: A variable name must start with a letter and can be a combination of letters, digits, period(.) and underscore(_). If it starts with period(.), it cannot be followed by a digit.


1 Answers

See lockBinding:

a <- 1 lockBinding("a", globalenv()) a <- 2 Error: cannot change value of locked binding for 'a' 
like image 87
hadley Avatar answered Sep 23 '22 22:09

hadley