[R] Defining functions - an interesting problem

Thomas Lumley tlumley at u.washington.edu
Wed May 27 16:36:18 CEST 2009


On Wed, 27 May 2009, utkarshsinghal wrote:

> 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".

Look at the arguments to rank()
> args(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
> f1(c(1,1,2,4), ties.method="min")
[1] 1 1 3 4

 	-thomas

Thomas Lumley			Assoc. Professor, Biostatistics
tlumley at u.washington.edu	University of Washington, Seattle




More information about the R-help mailing list