Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort a dataframe which only has one column but keep the same format

Have a dataframe with column, I just want to sort the numbers descending, and keep the format of file a dataframe with same column name and row names.

df <- structure(list(PC1 = c(0.799780548221684, 0.795730424977294, 
0.832486223147844, 0.781317878179846, 0.731616836371459, 0.806050349534197, 
0.843632585345136, 0.789598905674104, 0.817326659093254, -0.809254508281934, 
0.830418198715417, 0.835210246262256, 0.805101272196506, 0.82710709201306, 
0.829909348164638, 0.837074218693618, -0.78322895041798)), class = "data.frame", row.names = c("Q6Br1", 
"Q6Br2", "Q6Br3", "Q6Br4", "Q6Br5", "Q6Br6", "Q6Br7", "Q6Br8", 
"Q6Br9", "Q6Br10", "Q6Br11", "Q6Br12", "Q6Br13", "Q6Br14", "Q6Br15", 
"Q6Br16", "Q6Br17"))

When i try to sort it, it becomes a list. If i try to sort as dataframe, it loses the column name.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you want to use the column number to arrange the data, here are couple of options.

Using dplyr :

library(dplyr)
df %>% arrange(-pick(1L))
# Or
# df %>% arrange(desc(pick(1L)))

#              PC1
#Q6Br7   0.8436326
#Q6Br16  0.8370742
#Q6Br12  0.8352102
#Q6Br3   0.8324862
#Q6Br11  0.8304182
#Q6Br15  0.8299093
#Q6Br14  0.8271071
#Q6Br9   0.8173267
#Q6Br6   0.8060503
#Q6Br13  0.8051013
#Q6Br1   0.7997805
#Q6Br2   0.7957304
#Q6Br8   0.7895989
#Q6Br4   0.7813179
#Q6Br5   0.7316168
#Q6Br17 -0.7832290
#Q6Br10 -0.8092545

In base R :

df[order(-df[[1]]), , drop = FALSE]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading