Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

r - Usage of local variables

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...