使用局部变量

The*_*heo 9 scope r

问题:

如何在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!
Run Code Online (Sandbox Code Playgroud)

注意:此代码仅用于说明该想法.

这种做法具有以下优点:

  • 保持全局命名空间清洁;
  • 简化代码;
  • 消除歧义,特别是在没有初始化的情况下重新使用变量时.

在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!
Run Code Online (Sandbox Code Playgroud)

或者,以更加模糊的方式,声明一个匿名函数来阻止函数调用:

(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!
Run Code Online (Sandbox Code Playgroud)

是否有更优雅的方式来创建局部变量?

flo*_*del 13

使用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!
Run Code Online (Sandbox Code Playgroud)