[Bioc-devel] sorting objects with user-defined comparison function

Martin Morgan mtmorgan at fhcrc.org
Thu Sep 13 19:13:56 CEST 2007


Hi Wolfgang --

I guess these are S4 objects. One way might be, for a list l of
objects with slots x, y

> s1 <- sapply(l, slot, "x")
> s2 <- sapply(l, slot, "y")
> sorted <- l[order(s1, s2)]

slot access might be replaced by 'order_keygen' to generate whatever
the comparison value should be.

Here's a complete example:

> ## setup
> n <- 100
> l <- list(n)
> xi <- sample(1:10, n, replace=TRUE)
> yi <- sample(letters, n, replace=TRUE)
> setClass("A",
+          representation=representation(
+            x="numeric",
+            y="character"))
[1] "A"
> l <- mapply(new, Class="A", x=xi, y=yi)
> ## unorderd
> head(unlist(lapply(l, slot, "x"), use.names=FALSE))
[1] 10  1  5 10  7  7
> head(unlist(lapply(l, slot, "y"), use.names=FALSE))
[1] "k" "d" "z" "y" "z" "k"
> 
> ## sort
> s1 <- sapply(l, slot, "x")
> s2 <- sapply(l, slot, "y")
> sorted <- l[order(s1, s2)]
> 
> ## how'd we do?
> head(unlist(lapply(sorted, slot, "x"), use.names=FALSE))
[1] 1 1 1 1 1 1
> head(unlist(lapply(sorted, slot, "y"), use.names=FALSE))
[1] "d" "j" "k" "n" "q" "r"

Martin (with input from Seth)

Wolfgang Huber <huber at ebi.ac.uk> writes:

> Hi all,
>
> I hope I have not missed the obvious...: does anyone know a function in
> R (or in a package) that sorts the elements of a list based on a
> user-defined comparison function?
> -- 
> Best wishes
>  Wolfgang
>
> ------------------------------------------------------------------
> Wolfgang Huber  EBI/EMBL  Cambridge UK  http://www.ebi.ac.uk/huber
>
> _______________________________________________
> Bioc-devel at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/bioc-devel

-- 
Martin Morgan
Bioconductor / Computational Biology
http://bioconductor.org



More information about the Bioc-devel mailing list