局部变量的使用 [英] Usage of local variables
问题描述
问题:
如何在 r 代码的范围内定义局部变量.
How to define local variables within a scope in a r-code.
示例:
在 C++ 中,以下示例定义了一个作用域,在该作用域内声明的变量在外部代码中未定义.
In C++ the following example defines a scope, and variables declared within the scope are undefined in outside code.
{
vector V1 = getVector(1);
vector V1(= getVector(2);
double P = inner_product(V1, V2);
print(P);
}
// the variable V1, V2, P are undefined here!
注意:此代码仅用于说明想法.
这种做法的优点是:
- 保持全局命名空间干净;
- 简化代码;
- 消除歧义,特别是在未初始化的情况下重用变量时.
在 R 中,在我看来这个概念只存在于函数定义中.因此,为了重现之前的示例代码,我需要执行以下操作:
In R, it seems to me that this notion is only existent inside function definitions. So, in order to reproduce the previous example code, I would need to do something like this:
dummy <- function( ) {
V1 = c(1,2,3);
V2 = c(1,2,3);
P = inner_product(V1, V2);
print(P);
}
dummy( );
# the variable V1, V2, P are undefined here!
或者,以一种更加晦涩的方式,声明一个匿名函数来防止函数调用:
or, in an even more obscure way, declare a anonymous function to prevent the function call:
(function() {
V1 = c(1,2,3);
V2 = c(1,2,3);
P = inner_product(V1, V2);
print(P);
})()
# the variable V1, V2, P are undefined here!
问题
有没有更优雅的方法来创建局部变量?
Is there a more elegant way to create local variable?
推荐答案
使用 local
.使用您的示例:
Use local
. Using your example:
local({
V1 = c(1,2,3);
V2 = c(1,2,3);
P = inner_product(V1, V2);
print(P);
})
# the variable V1, V2, P are undefined here!
这篇关于局部变量的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!