在 R 中声明一个常量变量 [英] Declaring a Const Variable in R

查看:22
本文介绍了在 R 中声明一个常量变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 R 中工作,我想定义一些我(或我的合作者之一)无法更改的变量.在 C++ 中,我会这样做:

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" );

如何在 R 编程语言中执行此操作?

How do I do this in the R programming language?

为清楚起见进行我知道我可以在 R 中定义这样的字符串:

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

path = "/projects/current"

我真正想要的是一种语言结构,它可以保证任何人都无法更改与名为path"的变量相关联的值.

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

编辑以回复评论:

从技术上讲,const 是编译时保证是正确的,但在我看来,R 解释器会抛出停止执行并显示错误消息是有效的.例如,看看当您尝试为数字常量赋值时会发生什么:

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

所以我真正想要的是一种语言功能,它允许您只分配一次值,并且当您尝试为声明为 const 的变量分配新值时应该会出现某种错误.我不在乎错误是否发生在运行时,尤其是在没有编译阶段的情况下.这在技术上可能不是维基百科定义的常量,但它非常接近.看起来这在 R 编程语言中也是不可能的.

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.

推荐答案

lockBinding:

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

这篇关于在 R 中声明一个常量变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆