R order columns in a two-way table based on Row values

I am trying to order the columns within a two-way table I have created based upon row values. I have saved the two-way table as a table, thus putting it into a dataframe (I am using R). The below code should create a two-way table based on the built-in Iris data.

In the example I have given, see the attached picture, if you ordered the columns based upon the first row the column order should be setosa, virginica, Versicolor. The second row would order the columns virginica, Versicolor, Setosa. The third row would order the columns as Versicolor, virginica, setosa. so far the only solution I have is WinEUref19[,order(WinEUref19[nrow(WinEUref19),])]
,but this can only do the last row, is it possible to order the columns by the second or first row?

Two-way tables

Replicable code to get two-way table:

Data $ var2 <- iris $ Species
Data $ var2 <- sample(Data $ var2)
Df <-table(Data $ var2, iris $ Species)
rownames(Df) <- c("Row one","Row two", "Row three")
Df

I have been told a simple solution for this in case anyone else has this problem as other examples I found on forums are needlessly complex.
This solution is as followed, Df=name of the data frame you are using. If you want to sort by the second row use a 2 instead of a 1, row 3 a 3 instead of a one etc.

 Df[,order(Df[1,])]

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.