Anthony Nash
Anthony Nash

Reputation: 1137

How to reorder a list by the size of the data frame in each list element?

I have a list in which each element contains a data frame with n nrows. For example,

dfA <- data.frame(A=c("a","a","a"))
dfB <- data.frame(B=c("b","b"))
dfC <- data.frame(C=c("c","c","c"))
dfD <- data.frame(D=c("d","d","d","d"))
combineList <- list(dfA, dfB, dfC, dfD)

The current order of the list by nrow is 3, 2, 3, 4. I would like to return a list but reordered so that the list element with the data frame with the most rows come first. The list element with the data frame with the least number of rows comes last. I'm not sure how to treat equal nrow list element entries.

How can I do this?

Upvotes: 0

Views: 239

Answers (1)

MichaelChirico
MichaelChirico

Reputation: 34773

combineList[order(sapply(combineList, nrow), decreasing = TRUE)]

Crux being that you can sapply nrow across your list to get a vector then order this vector to get indices in the order you desire:

sapply(combineList, nrow)
# [1] 3 2 3 4
order(sapply(combineList, nrow), decreasing = TRUE)
# [1] 4 1 3 2

Upvotes: 3

Related Questions