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:
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?
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With