Sorting a table with R
34,488
Solution 1
You need to sort
by the names of the table
output
tbl <- table(x)
tbl[order(-as.numeric(names(tbl)))]
Solution 2
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))
Solution 3
Here is another solution; it is based on simple R code and it works for any types of data, e.g. numeric or string. Hope it helps:
x <- c("100","100","300","200","200","200")
t <- table(x)
# you can sort based on any order you prefer
order_ind <- c("300","100","200")
t[order_ind]
![Gotey](https://i.stack.imgur.com/hcnec.jpg?s=256&g=1)
Comments
-
Gotey about 4 years
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.