Reputation: 55
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?
Replciable code:
Data <- iris
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
setosa versicolor virginica
Row one 14 19 17
Row two 22 15 13
Row three 14 16 20
Upvotes: 1
Views: 724
Reputation: 2904
Yes, you can order by any row. Just compute the order of the values and set the resulting vector as a selection criterion for the columns.
> Df[,order(Df[1,])]
setosa versicolor virginica
Row one 15 17 18
Row two 18 15 17
Row three 17 18 15
> Df[,order(Df[2,])]
versicolor virginica setosa
Row one 17 18 15
Row two 15 17 18
Row three 18 15 17
> Df[,order(Df[3,])]
virginica setosa versicolor
Row one 18 15 17
Row two 17 18 15
Row three 15 17 18
Upvotes: 0
Reputation: 2551
You basically have the answer already. you can order the table by the first row like this:
Df[,order(Df[1,])]
By the second row like this:
Df[,order(Df[2,])]
and so on.
Upvotes: 0