Search code examples
rfactorsrecode

How to Change R factor value without changing levels?


Today I wanted to change values of my factor in R without changing the levels and order. I'm going crazy!

My variable looks like this:

str(df_2$sex)
 Factor w/ 2 levels "MALE", "FEMALE": 1 1 1 2 1 2 1 2 2 1 2 1

I would like to change the value of "MALE" to = 0 and of "FEMALE" to 1. It should look like this:

str(df_2$sex)
 Factor w/ 2 levels "MALE", "FEMALE": 0 0 0 1 0 1 0 1 1 0 1 0

Is there a way to do this without defining the variable as numeric?

Thanks in advance.


Solution

  • Thanks for the comments. Sometimes, you want to implement things you don't need. What have I learned:

    • R counts from 1.
    • Factors are practical and hardly need any processing.
    • I urgently need to look at the package forcats.

    With kind regards aeoneo