Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: variable and function of same name

Tags:

function

r

R allows function and variable to have same name. I tested it with lm function but when i created my own function, k, i get an error. Could someone tell what is my error

> k<-function(d){2*d}
> k(5)
[1] 10
> k
function(d){2*d}
> k<-c(1,2)
> k
[1] 1 2
> k(2)
Error: could not find function "k"

works fine with lm function

> lm<-2
> lm
[1] 2
> lm(airquality$Ozone~., data=airquality)

Call:
lm(formula = airquality$Ozone ~ ., data = airquality)

Coefficients:
(Intercept)      Solar.R         Wind         Temp        Month          Day  
  -64.11632      0.05027     -3.31844      1.89579     -3.03996      0.27388  

> lm
[1] 2
like image 814
learnlifelong Avatar asked Mar 03 '26 15:03

learnlifelong


1 Answers

As @AdamQuek commented, I believe that the reason why lm <- 2 does not overwrite the lm() function in the stats package is because that function exists in a different namespace. When you defined your function k(), you defined it in the local namespace, and then you overwrote it in the local namespace.

R has a set of rules for determining the order of which namespace it uses when evaluating variables/functions. If you had defined lm() locally as:

lm <- function(x) { print(x) }

Then calling lm("Hello World") would indeed print "Hello World." If you still wanted to use the version of lm() from the stats package, you could use the fully qualified name of that function:

stats::lm(...)

In other words, if you don't qualify the function, R will first search the local namespace, and then it will search in libraries you have loaded.

And as Alistaire commented, please don't do this. In any programming language, you should avoid naming user defined functions after functions in commonly used packages/libraries.

like image 181
Tim Biegeleisen Avatar answered Mar 05 '26 03:03

Tim Biegeleisen