使用局部变量

时间:2013-02-10 00:08:45

标签: r scope

问题:

如何在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!

问题

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

2 个答案:

答案 0 :(得分: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!

答案 1 :(得分:1)

您可以创建一个新的environment,其中可以定义您的变量;这就是函数中局部范围的定义方式。

您可以阅读有关此here

的更多信息

检查environment的帮助,即输入您的R控制台?environment