Search code examples
rsortingcategorical-data

How to maintain order of levels after factorizing column in R


I have a permutation of different electrodes (25x25=625) from frontal to parietal.

> head(grph_test)
  Elec1 Elec2
1   Fp1   Fp1
2   Fp1   Fp2
3   Fp1    F7
4   Fp1    F3
5   Fp1    Fz
6   Fp1    F4

The thing is I want to factorize the columns but it changes the level order to alphabetical, which is not useful for my purpose.

> test$Elec1 <- factor(test$Elec1, ordered = is.ordered(test$Elec1))
> levels(grph_test$Elec1)
 [1] "C3"  "C4"  "CP1" "CP2" "CP5" "CP6" "Cz"  "F3"  "F4"  "F7"  "F8"  "FC1" "FC2" "FC5" "FC6" "Fp1" "Fp2" "Fz"  "Oz"  "P3"  "P4"  "P7"  "P8" 
[24] "POz" "Pz" 

While my expectation was they would end up in the same order as the original column, which follows something like the following list:

"Fp1","Fp2","F7","F3","Fz","F4","F8","FC5","FC1","FC2","FC6","C3","Cz","C4","CP5","CP1","CP2","CP6","P7","P3","Pz","P4","P8","POz","Oz"

I thought, according to the documentation, ordered = is.ordered(test$Elec1) argument would be capable of mantaining the original order, but as you can see it does not.

Any idea why? Thank you!


Solution

  • We can use unique in the levels argument of factor as unique returns the unique values from the first occurrence of that element, thus it maintains the same order of occurrence as in the original data

    test$Elec1 <- factor(test$Elec1, levels = unique(test$Elec1))
    

    NOTE: is.ordered returns a logical output