限制变量范围 [英] Limiting variable scope

查看:44
本文介绍了限制变量范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个函数,它限制了 R 变量的范围.例如,

I'm trying to write a function, which limits the scope of R variables. For example,

source("LimitScope.R")
y = 0
f = function(){
   #Raises an error as y is a global variable
   x = y
}

我想测试变量环境,但不确定如何执行此操作.

I thought of testing the variable environment, but wasn't really sure of how to do this.

为什么

我教本科生R.在他们的前几个实践中,他们中的一些人总是忘记变量作用域,因此他们提交的函数不起作用.例如,我总是得到类似的信息:

I teach R to undergrads. In their first couple of practicals a few of them always forget about variable scope, so their submitted functions don't work. For example, I always get something like:

n = 10
f = function(x){
  #Raises an error
  #as I just source f and test it for a few test cases.
  return(x*n)
}

我正在寻找一个可以关闭"范围的快速功能.正如您所想象的那样,它不必特别强大,因为它只会用于少数实践.

I was after a quick function that would 'turn off' scope. As you can imagine it doesn't have to be particularly robust, as it would just be offered for the few practicals.

推荐答案

我不确定您是否想这样做,但是 local() 函数应该会有所帮助,就像codetools 库.

I'm not sure that you want to do this in general, but the local() function should help, as should the codetools library.

在你的例子中,试试

f = local( function() { ... }, baseenv())

它并不完全符合您的要求,但应该能让您更接近.

It does not do exactly what you want, but it should get you closer.

这篇关于限制变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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