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.
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.
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))
You need to sort
by the names of the table
output
tbl <- table(x)
tbl[order(-as.numeric(names(tbl)))]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With