How does R know to use a function, if that functions name has been reassigned to a value?

Viewed 846

I know it's good practice not to use names from the global namespace when naming variables, but what happens when you do this accidentally?

I thought I would lose the previous object but R seems to have some trickery under the hood:

print(sd)
#> function (x, na.rm = FALSE) 
#> sqrt(var(if (is.vector(x) || is.factor(x)) x else as.double(x), 
#>     na.rm = na.rm))
#> <bytecode: 0x0000000017e687b8>
#> <environment: namespace:stats>

sd <- 12.2

print(sd)
#> [1] 12.2

sd(1:10)
#> [1] 3.02765

So now R knows there is both a length one double vector called sd and a stats function sd() in the global namespace?

Or when I call sd(1:10) the interpreter automatically expands this to sd.default()? But how does R know to look for a default method on sd as it's now a vector? So functions and variables stored in different places in memory can be referenced by the same name?

obviously_a_user_defined_variable <- 257
obviously_a_user_defined_variable(1:10)
#> Error in obviously_a_user_defined_variable(1:10): could not find 
#  function "obviously_a_user_defined_variable"
2 Answers

R has separate namespaces for functions and variables. Depending on the context in which a name occurs, R will look up the name in one namespace or in the other.

For instance, the expression sd(1:10) is a call and the first element in a call must be the name of a function. Therefore, in this case, R will look for a function named sd.

On the other hand, the expression sd is not a call but a name, which could be either the name of a variable or the name of a function. In this case R will look first for the first object in the search path named sd regardless of whether it's a function or another type of object.

Related