Let’s create some factors first:
F1 <- factor(c(1,2,20,10,25,3))
F2 <- factor(paste0(F1, " years"))
F3 <- F2
levels(F3) <- paste0(sort(F1), " years")
F4 <- factor(paste0(F1, " years"), levels=paste0(sort(F1), " years"))
then take a look at them:
> F1
[1] 1 2 20 10 25 3
Levels: 1 2 3 10 20 25
> F2
[1] 1 years 2 years 20 years 10 years 25 years 3 years
Levels: 1 years 10 years 2 years 20 years 25 years 3 years
> F3
[1] 1 years 3 years 10 years 2 years 20 years 25 years
Levels: 1 years 2 years 3 years 10 years 20 years 25 years
> F4
[1] 1 years 2 years 20 years 10 years 25 years 3 years
Levels: 1 years 2 years 3 years 10 years 20 years 25 years
First I note that the “expected” order of the levels in F2 is not similar to F1. Taking a look at factor documentation reveals why: the levels are created by first sorting the input. In the case of F2, these are the strings, where sorting takes length into account (?).
What is harder for me to understand is the difference in setting the levels between F3 and F4. In F3 I set the levels after the factor is created while in F4 I set them explicitly when creating the factor. In F3, the use of levels()<- isn’t purely a relabel of the levels, but neither does it reorder them the way I expected.
Can someone explain the difference?
F1uses numeric sorting, as you figured out yourself.F2uses lexicographic sorting, first comparing the first character, breaking ties using the second, and so on, which is why"10 years"is between"1 years"and"2 years".F4is created from a character vector, but with an explicit list of possible factors. So that list is taken (without sorting) and identified with the numbers 1 through 6. Then every item of your input is compared against the set of possible levels, and the associated number is stored. After all, a factor is simply a bunch of numbers (as.numericwill show them to you) associated with a list of levels used for printing. SoF4gets printed just likeF2, but its levels are sorted differently.F3was created from F2, so its levels were unsorted initially. The assignment only replaces the set of level names, not the numbers in the vector. So you can think of this as renaming existing levels. If you look at the numbers, they will match those fromF2, whereas the names associated, and the order of names in particular, matches that fromF4.As your question claims that this was not purely a relabel: yes, it is a pure relabel, you obtain
F3fromF2using the following changes (in both rows of the printout):The
strfunction is also a good tool to look at the internal representation of a factor.