Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort list of lists by length of member lists

Tags:

r

I have output from a package (apcluster) that comes as a S4 object type. One of the members is a list of lists determining the members of each cluster found. I want to sort that list by the length (largest clusters).

My code right now looks like

ap.result <- apcluster(args)
clusters <- ap.result@cluster #list of lists

I can then access individual members of clusters by clusters[[i]] but the order is semi-random. If I unlist(clusters) then I get a vector without knowing which sub-list it came from.

How can I sort ap.result@cluster to be ordered by longest member list to shortest member list?

like image 758
Ian Fiddes Avatar asked Mar 05 '14 21:03

Ian Fiddes


2 Answers

Version 1.3.4 of the package has been released on CRAN today (the Windows and Mac OS X binaries may take 1-2 more days to be online). Inspired by Ian's request, the new version includes a sort() method for rearranging the cluster according to a given sorting criterion. The solution to Ian's question would now be the following:

sort(ap.result, decreasing=TRUE, sortBy="size")
like image 119
UBod Avatar answered Sep 18 '22 09:09

UBod


As per the comments, here is the solution:

clusters[order(sapply(clusters,length),decreasing=T)]
like image 37
Ian Fiddes Avatar answered Sep 20 '22 09:09

Ian Fiddes