函数内部的attach()
我想为函数提供 params 参数,然后附加它,以便每次引用列表元素 a 时都可以使用 a 而不是 params$a 。
run.simulation<-function(model,params){
attach(params)
#
# Use elements of params as parameters in a simulation
detach(params)
}
这有问题吗?如果我定义了一个名为 c 的全局变量,并且还定义了列表 "params" 中一个名为 c 的元素,那么在附加命令之后将使用其值?
I'd like to give a params argument to a function and then attach it so that I can use a instead of params$a everytime I refer to the list element a.
run.simulation<-function(model,params){
attach(params)
#
# Use elements of params as parameters in a simulation
detach(params)
}
Is there a problem with this? If I have defined a global variable named c and have also defined an element named c of the list "params" , whose value would be used after the attach command?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Noah 已经指出使用 Attach 是一个坏主意,即使您在一些示例和书籍中看到它。有办法解决。您可以使用名为
with
的“本地附加”。在诺亚的虚拟示例中,这看起来会产生相同的结果,但更整洁。
Noah has already pointed out that using attach is a bad idea, even though you see it in some examples and books. There is a way around. You can use "local attach" that's called
with
. In Noah's dummy example, this would look likewhich will yield identical result, but is tidier.
另一种可能性是:
Another possibility is:
解决此类范围问题的最简单方法通常是尝试一些简单的方法:
如您所见,R 在此处选取全局属性
a
。尽可能避免使用
attach
和detach
几乎总是一个好主意——作用域最终会变得很难处理(顺便说一句,最好避免命名变量c
——R 通常会弄清楚你所指的是什么,但是还有很多其他字母,为什么要冒险呢?)。此外,我发现使用附加/分离的代码几乎无法破译。Easiest way to solve scope problems like this is usually to try something simple out:
As you can see, R is picking up the global attribute
a
here.It's almost always a good idea to avoid using
attach
anddetach
wherever possible -- scope ends up being tricky to handle (incidentally, it's also best to avoid naming variablesc
-- R will often figure out what you're referring to, but there are so many other letters out there, why risk it?). In addition, I find code using attach/detach almost impossible to decipher.Jean-Luc 的回答对我有很大帮助,因为我有一个 data.frame
Dat
而不是 OP 中指定的列表:for (v in 1:ncol(Dat)) 分配(名称(Dat)[v],Dat[,v])
Jean-Luc's answer helped me immensely for a case that I had a data.frame
Dat
instead of the list as specified in the OP:for (v in 1:ncol(Dat)) assign(names(Dat)[v], Dat[,v])