问题:
如何在R代码的范围内定义局部变量。
示例:
在C++中,以下示例定义了一个范围,并且在该范围内声明的变量在外部代码中未定义。
{
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中,在我看来,这个概念仅存在于函数定义中。因此,为了重现前面的示例代码,我需要执行以下操作:
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!
或者,以更加晦涩的方式,声明一个匿名函数以防止该函数调用:
(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!
问题
有没有更优雅的方法来创建局部变量?
最佳答案
使用local
。使用您的示例:
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!
关于r - 局部变量的用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14793113/