Ian Fiddes
Ian Fiddes

Reputation: 3011

Sort list of lists by length of member lists

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?

Upvotes: 6

Views: 2998

Answers (2)

UBod
UBod

Reputation: 845

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

Upvotes: 5

Ian Fiddes
Ian Fiddes

Reputation: 3011

As per the comments, here is the solution:

clusters[order(sapply(clusters,length),decreasing=T)]

Upvotes: 5

Related Questions