Extract the factor's values positions in level

If you convert a factor to integer, you get the position in the levels:

as.integer(fdata)
## [1] 1 2 1 1 3

In certain situations, this is counter-intuitive:

f <- factor(2:4)
f
## [1] 2 3 4
## Levels: 2 3 4
as.integer(f)
## [1] 1 2 3

Also if you silently coerce to integer, for example by using a factor as a vector index:

LETTERS[2:4]
## [1] "B" "C" "D"
LETTERS[f]
## [1] "A" "B" "C"

Converting to character before converting to integer gives the expected values. See ?factor for details.

Tags:

R

R Factor