Declaring a Const Variable in R

前端 未结 6 996
耶瑟儿~
耶瑟儿~ 2020-12-05 00:07

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( \"/         


        
6条回答
  •  隐瞒了意图╮
    2020-12-05 00:25

    (Edited for new idea:) The bindenv functions provide an

    experimental interface for adjustments to environments and bindings within environments. They allow for locking environments as well as individual bindings, and for linking a variable to a function.

    This seems like the sort of thing that could give a false sense of security (like a const pointer to a non-const variable) but it might help.

    (Edited for focus:) const is a compile-time guarantee, not a lock-down on bits in memory. Since R doesn't have a compile phase where it looks at all the code at once (it is built for interactive use), there's no way to check that future instructions won't violate any guarantee. If there's a right way to do this, the folks at the R-help list will know. My suggested workaround: fake your own compilation. Write a script to preprocess your R code that will manually substitute the corresponding literal for each appearance of your "constant" variables.

    (Original:) What benefit are you hoping to get from having a variable that acts like a C "const"?

    Since R has exclusively call-by-value semantics (unless you do some munging with environments), there isn't any reason to worry about clobbering your variables by calling functions on them. Adopting some sort of naming conventions or using some OOP structure is probably the right solution if you're worried about you and your collaborators accidentally using variables with the same names.

    The feature you're looking for may exist, but I doubt it given the origin of R as a interactive environment where you'd want to be able to undo your actions.

提交回复
热议问题