Usage of local variables

心不动则不痛 提交于 2019-12-29 06:49:09

问题


Problem:

How to define local variables within a scope in a r-code.

Example:

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!

Note: This code is only to illustrate the idea.

This practice has the advantages of:

  • Keeping the global namespace clean;
  • simplifying code;
  • removing ambiguities, specially when a variable is re-used without initialization.

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!

Question

Is there a more elegant way to create local variable?


回答1:


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!



回答2:


You can create a new environment where your variable can be defined; this is how the local scope within a function is defined.

You can read more about this here

check the help for environment as well i.e. type in your R console ?environment



来源:https://stackoverflow.com/questions/14793113/usage-of-local-variables

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!