[R] Defining functions - an interesting problem

utkarshsinghal utkarsh.singhal at global-analytics.com
Wed May 27 16:11:47 CEST 2009


I define the following function:
(Please don't wonder about the use of this function, this is just a 
simplified version of my actual function. And please don't spend your 
time in finding an alternate way of doing the same as the following does 
not exactly represent my function. I am only interested in a good 
explanation)

 > f1 = function(x,ties.method="average")rank(x,ties.method)
 > f1(c(1,1,2,4), ties.method="min")
[1] 1.5 1.5 3.0 4.0

I don't know why it followed ties.method="average".
Anyways I randomly tried the following:

 > f2 = function(x,ties.method="average")rank(x,ties.method=ties.method)
 > f2(c(1,1,2,4), ties.method="min")
[1] 1 1 3 4
Now, it follows the ties.method="min"

I don't see any explanation for this, however, I somehow mugged up that 
if I define it as in "f1", the ties.method in rank function takes its 
default value which is "average" and if I define as in "f2", it takes 
the value which is passed in "f2".

But even all my mugging is wasted when I tested the following:

 > h = function(x, a=1)x^a
 > g1 = function(x, a=1)h(x,a)
 > g1(x=5, a=2)
[1] 25

 > g2 = function(x, a=1)h(x,a=a)
 > g2(x=5, a=2)
[1] 25

Here in both the cases, "h" is taking the value passed through "g1", and 
"g2".

Any comments/hints can  be helpful.

Regards
Utkarsh




More information about the R-help mailing list