rfactorslevels

A problem when releveling a factor to the default order?


I have this df

df = data.frame(x = 1:3)

converted to a factor

df$x = factor(df$x)

the levels by default are

str(df)

now let's make level 2 as the reference level

df$x = relevel(df$x,ref=2)

everything till now is ok. but when deciding to make the level 1 again as the default level it's not working

df$x = relevel(df$x,ref=2)

str(df)


df$x = relevel(df$x,ref=1)

str(df)

Appreciatethe help.


Solution

  • From ?relevel,

         ref: the reference level, typically a string.
    

    I'll key off of "typically". Looking at the code of stats:::relevel.factor, one key part is

        if (is.character(ref)) 
            ref <- match(ref, lev)
    

    This means to me that after this expression, ref is now (assumed to be) an integer that corresponds to the index within the levels. In that context, your ref=1 is saying to use the first level by its index (which is already first).

    Try using a string.

    relevel(df$x,ref=1)
    # [1] 1 2 3
    # Levels: 2 1 3
    relevel(df$x,ref="1")
    # [1] 1 2 3
    # Levels: 1 2 3