Reorder data frame columns by values in first row

30 Views Asked by At

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

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),])]
1

There are 1 best solutions below

1
Onyambu On BEST ANSWER
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