Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a table with R

Tags:

sorting

r

I have a table in R and I sort it like this:

> x<-c("100","100","300","200","200","200")
> x
[1] "100" "100" "300" "200" "200" "200"
> table(x)
x
100 200 300 
  2   3   1 
> sort(table(x))
x
300 100 200 
  1   2   3 

But my problem is that I would like to have it sorted by the numbers 300, 100, and 200. So I would like to know how to do it.

like image 475
Gotey Avatar asked Apr 02 '16 16:04

Gotey


People also ask

Can you sort data in R?

There is a function in R that you can use (called the sort function) to sort your data in either ascending or descending order. The variable by which sort you can be a numeric, string or factor variable. You also have some options on how missing values will be handled: they can be listed first, last or removed.


2 Answers

You can transfer the table to data.frame, and then use arrange function from the package dplyr.

table(x) %>% 
        as.data.frame() %>% 
        arrange(desc(Freq))
like image 61
Zhiliang Lin Avatar answered Oct 17 '22 11:10

Zhiliang Lin


You need to sort by the names of the table output

tbl <- table(x)
tbl[order(-as.numeric(names(tbl)))]
like image 28
akrun Avatar answered Oct 17 '22 10:10

akrun