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

Reorder data frame columns by values in first row

I have a data frame in R. I’d like to reorder the columns based on values in the first row. All entries in the data frame contain numeric data. I thought this would be straight forward and analogous to ordering rows based on a column value. I.e., I tried
df <- df[,order(df[1,])]

However I receive an error.
Error in xtfrm.data.frame(x) : cannot xtfrm data frames

I quick google search landed me on someone asking this exact same question a decade ago here

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

I tried copying and pasting the answer into R studio to see if it worked and I ran into the same error. What gives?

x <- structure(list(aa = c(3L, 5L, 7L, 33L), bb = c(4L, 4L, 8L, 63L),
cc = c(5L, 3L, 6L, 55L)), .Names = c("aa", "bb", "cc"),
class = "data.frame", row.names = c("1", "2", "3", "100"))
x[,order(-x[nrow(x),])]

>Solution :

x[,order(-unlist(x[1,]))]
    cc bb aa
1    5  4  3
2    3  4  5
3    6  8  7
100 55 63 33

x[,order(-unlist(x[nrow(x),]))]
    bb cc aa
1    4  5  3
2    4  3  5
3    8  6  7
100 63 55 33
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