Skip to content

Defining functions - an interesting problem

5 messages · utkarshsinghal, Thomas Lumley, Gavin Simpson +1 more

#
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
#
On Wed, 27 May 2009, utkarshsinghal wrote:

            
Look at the arguments to rank()
function (x, na.last = TRUE, ties.method = c("average", "first",
     "random", "max", "min"))

When you do rank(x, ties.method) you are passing "min" as the second 
argument to rank(), which is the na.last argument, not the ties.method 
argument.  This didn't give an error message because there weren't any NAs 
in your data.

You want
f1 = function(x,ties.method="average")rank(x,ties.method=ties.method)
which gives
[1] 1 1 3 4

 	-thomas

Thomas Lumley			Assoc. Professor, Biostatistics
tlumley at u.washington.edu	University of Washington, Seattle
#
On Wed, 2009-05-27 at 19:41 +0530, utkarshsinghal wrote:
What is the second argument of rank? It is not ties.method. You passed
"min" to na.last, not ties.method. You need to name the argument if you
are not passing in all arguments and in the correct order.
Why randomly - ?rank tells you the argument is ties.method so you should
set it to ties.method: times.method = ties.method in your call to rank.
Because you aren't passing ties.method as the same argument in f1 and
f2. In f1 you are passing ties.method to na.last, in f2 you do it
correctly.
Here there are only two arguments and you supplied them in the correct
place when you supplied them un-named.

HTH

G
#
Yeah, seems so obvious now. What a blunder, poor me.
Perfect explanation. Thanks
Thomas Lumley wrote: