In the .GlobalEnv, I defined the following variable and function
x = 0;
foo <- function(t=x) {x=1; t}
When I called the function in the following ways
foo() # gives 1
foo(t=x) # gives 0
Can anyone help explain this? Thanks!!!
A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the calling function doesn't provide a value for the argument. In case any value is passed, the default value is overridden.
Adding Default Value in R If the value is passed by the user, then the user-defined value is used by the function otherwise, the default value is used. Below is an implementation of function with default value. # a is divisible by b or not.
Parameter values to functions are stored on the stack as well, pushed immediately before the return address. Everything what lives on the stack (local variables, parameters etc.) can live in registers as well.
Any number of arguments in a function can have a default value.
To make the comment into an answer:
In the first case, the function knows it needs to pass x
to t
. It is looking for x
in its lexical scope and finds x=1
. In the second case, you pass x=0
from the global environment, thus it doesn't look for it in the lexical scope again and passes it straight to t
.
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