How to sort all the columns all together of a dataframe using R?
I would like to sort in descending order all columns of data.frame. The dataframe looks like
mat
. [,D1] [,D2] [,Dn]
[D1,] 5 1 6
[D2,] 10 3 1
[D3,] 8 8 1
[D4,] 8 9 9
[D5,] 3 7 3
[D6,] 8 8 5
[D7,] 10 10 2
[D8,] 8 10 7
[D9,] 10 1 9
[Dn,] 9 4 5
I know to sort it based on a single column by using mat <- mat[order(mat$D1),], but I have 1000 columns. How do I sort all 1000 keeping the row name same.
• 4,204 views
•
link
1 answer
If you want to sort EACH column independently of the other, you can use the apply function with sort.
mat_sorted <- apply(mat, 2, sort, decreasing=F)
2-> Apply on columnssort-> built-in sorting functiondecreasing-> False or True
EDIT:
mat
![]()
mat_sorted
![]()
I hope that what you are looking for, but it is what I understood. :)
• 1 views
•
link
Log in to answer this question.
"Descending order of all columns" isn't a coherent concept unless you want the rows to get jumbled. Do you mean, "I want to order by column 1, with ties broken according to column 2 (and so on)?"
Hello Paul!
We believe that this post does not fit the main topic of this site.
Not connected to bioinformatics.
For this reason we have closed your question. This allows us to keep the site focused on the topics that the community can help with.
If you disagree please tell us why in a reply below, we'll be happy to talk about it.
Cheers!