Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
724 views
in Technique[技术] by (71.8m points)

statistics - 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.

question from:https://stackoverflow.com/questions/936748/declaring-a-const-variable-in-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

See lockBinding:

a <- 1
lockBinding("a", globalenv())
a <- 2
Error: cannot change value of locked binding for 'a'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...