Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: How default argument is passed to a function?

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!!!

like image 408
Eric Avatar asked Oct 20 '14 18:10

Eric


People also ask

How default arguments are passed to functions?

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.

How do you pass a default value for an argument in R?

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.

Where are the argument passed to a function stored?

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.

Can a function argument have default value?

Any number of arguments in a function can have a default value.


1 Answers

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.

like image 152
Ben Avatar answered Sep 19 '22 15:09

Ben