rr-factor

Rename one level of a factor in R


I'm attempting to rename the level A of factor column1 in the dataframe df in R. My current approach is this:

levels(df[!is.na(df$column1) & df$column1 == 'A',]) <- 'B'

which doesn't throw any errors or warnings but is completely ineffective.

B is not an already existing level (which from trial and error I came to suspect was important), so the following, my first attempt, didn't work either

df[!is.na(df$column1) & df$column1 == 'A', 'column1'] <- 'B'

Could anyone guide me to the correct approach?


Solution

  • I was going to suggest

    levels(df$column1)[levels(df$column1)=="A"] <- "B"
    

    or use the utility function plyr::revalue:

    library("plyr")
    df <- transform(df,
              column1=revalue(column1,c("A"="B")))
    

    transform() is a little sugar that's not necessary; you could use df$column1 <- revalue(df$column1(...))

    For completeness, car::recode also works, although I find it a little bit clunkier than plyr::revalue (because the recoding is specified as a quoted string).

    car::recode(df$column1,"'A'='B'")
    

    More recently forcats::fct_recode() can also be used for this.