1
votes

I have two columns with levels that are nested. By nested I mean that the factors in column 2 are dependent upon the values of column 1. I would like to order the factor levels in column 1 alphabetically. I would like the factor levels in column 2 to be alphabetically ordered after the alphabetical order of column 1.

data<-as.data.frame(cbind(c("A","B","D","C","A","B","D","C","A","B","C","D"),
                      c("Alpha","Beta","Gamma","Delta","Zeta","Chi","Omega",
                                  "Delta","Alpha","Gamma","Beta","Zeta")))

data<-data[with(data, order(factor(levels(data$V1))), 
                                      factor(levels(data$V2))), ]

I tried to order the factor levels as described above, but the second column is not ordered after the first; it is just alphabetically ordered on its own. I know I can manually type in the order of levels that I desire, but I am after something that doesn't require that.

Thank you.

2
They are already factors. So you should just order by their values.The order call should just be order(V1,V2) > The effect you are seeing comes from the fact that levels(fac) is generally a lot shorter than fac itself.IRTFM
data<-data[order(data$V1,data$V2), ]Metrics
I should say that I would like the factor levels reorded for use during graphing using ggplot2. So far, none of these functions are preserved when I plot the new ordered data frameK. Brannen

2 Answers

0
votes

Like the following?

library(dplyr)
arrange(data, V1, V2)
   V1    V2
1   A Alpha
2   A Alpha
3   A  Zeta
4   B  Beta
5   B   Chi
6   B Gamma
7   C  Beta
8   C Delta
9   C Delta
10  D Gamma
11  D Omega
12  D  Zeta
0
votes

data<-data[order(data$V1,data$V2), ] #should work

> data
   V1    V2
1   A Alpha
9   A Alpha
5   A  Zeta
2   B  Beta
6   B   Chi
10  B Gamma
11  C  Beta
4   C Delta
8   C Delta
3   D Gamma
7   D Omega
12  D  Zeta