[Rd] Can't make sort generic in quantile (S3)

Gabor Grothendieck ggrothendieck at gmail.com
Mon Aug 7 04:35:11 CEST 2006


Try redefining quantile.default:

	environment(quantile.default) <- .GlobalEnv

For example, if you run the following in a fresh session it should
print out X showing that the newly defined sort was invoked:

	environment(quantile.default) <- .GlobalEnv
	sort <- function(x, ...) { cat("X\n"); base::sort(x, ...) }
	quantile(1:100)

That being said, its not really a good idea to redefine functions
from the core of R.  Furthermore, in this case quantile is generic
and sort is not generic so you would be better off creating a method
for quantile rather than sort.  If you do want a generic sort
then use a different name such as SORT or just define sort.whatever
and have the user to run that directly.

Also if the only reason you are creating a generic for sort is
so that it can be used in quantile then you could do something
along these lines assuming your new class is X:

	quantile.X <- function(x, ...) {
		sort <- function(x, ...) { cat("X\n"); base::sort(x, ...) }
		environment(quantile.default) <- environment()
		quantile.default(x, ...)
	}

                # test it out
	x <- structure(1:100, class = "X")
	quantile(x)

which will cause the redefined sort to be used in quantile and
is a bit safer since its effect is restricted to that.


On 8/6/06, miguel manese <jjonphl at gmail.com> wrote:
> Hello all,
>
> In my package I made sort() generic as follows:
>
> sort.default <- sort; sort <- function(x, ...) UseMethod("sort");
> formals(sort.default) <- c(formals(sort.default), alist(...=))
>
> then added a sort for my S3 class
>
> sort.sqlite.vector <- function(x, decreasing=FALSE, ...) {
>    .Call("sdf_sort_variable", x, as.logical(decreasing))
> }
>
> In the stats::quantile() function, sort() is still bound to the
> original definition. I got the following error when calling quantile:
>
> Error in sort(x, partial = unique(c(lo, hi))) :
>        'x' must be atomic
>
> However, when I copy quantile's def'n (say as myquantile in
> myquantile.R), source() it then do myquantile(x), I get the results.
>
> Thanks,
> M. Manese
>
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
>



More information about the R-devel mailing list