User981636
User981636

Reputation: 3621

Order/Sort/Rank a table

I have a table like this

table(mtcars$gear, mtcars$cyl)

I want to rank the rows by the ones with more observations in the 4 cylinder. E.g.

     4  6  8
  4  8  4  0
  5  2  1  2
  3  1  2 12

I have been playing with order/sort/rank without much success. How could I order tables output?

Upvotes: 3

Views: 105

Answers (3)

P1storius
P1storius

Reputation: 947

In the same scope as Milan, but using the order() function, instead of looking for names() in a sort()-ed list. The [,1] is to look at the first column when ordering.

table(mtcars$gear, mtcars$cyl)[order(table(mtcars$gear, mtcars$cyl)[,1], decreasing=T),]

Upvotes: 0

milan
milan

Reputation: 4970

Could try this. Use sort for the relevant column, specifying decreasing=TRUE; take the names of the sorted rows and subset using those.

table(mtcars$gear, mtcars$cyl)[names(sort(table(mtcars$gear, mtcars$cyl)[,1], dec=T)), ]

     4  6  8
  4  8  4  0
  5  2  1  2
  3  1  2 12

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388982

We can convert table to data.frame and then order by the column.

sort_col <- "4"
tab <- as.data.frame.matrix(table(mtcars$gear, mtcars$cyl))
tab[order(-tab[sort_col]), ]
# OR tab[order(tab[sort_col], decreasing = TRUE), ]

#  4 6  8
#4 8 4  0
#5 2 1  2
#3 1 2 12

If we don't want to convert it into data frame and want to maintain the table structure we can do

tab <- table(mtcars$gear, mtcars$cyl)
tab[order(-tab[,dimnames(tab)[[2]] == sort_col]),]

#     4  6  8
#  4  8  4  0
#  5  2  1  2
#  3  1  2 12

Upvotes: 2

Related Questions