Search code examples
rtidyverseforcats

Recoding factor using fct_recode: "Unknown levels in `f`"


I have created the following factor with success:

conti <- factor(
  c("Europe", "Africa", "Africa", "Asia", "S.America"), #Every single observation is registered
  levels = c("Africa", "Asia","Europe", "S.America") #Every possible category is registred
)

I am trying to recode the levels using the forcats function 'fct_recode':

conti <- fct_recode(conti,
                    "S.America" = "S. Amerika",
                    "Europe" = "Europa",
                    "Asia" = "Asien",
                    "Africa" = "Afrika")

Doing so, I receive the following error-code:

Unknown levels in `f`: S. Amerika, Europa, Asien, Afrika

Any idea what is happening here?


Solution

  • You get a warning message on them since you have assigned new factor levels incorrectly. Try,

    forcats::fct_recode(conti,
                         "S. Amerika" = "S.America",
                         "Europa" = "Europe",
                         "Asien" = "Asia",
                         "Afrika" = "Africa")
    
    #[1] Europa     Afrika     Afrika     Asien      S. Amerika
    #Levels: Afrika Asien Europa S. Amerika