Michael Ohlrogge
Michael Ohlrogge

Reputation: 10990

Set Factor Reference Level Upon Creation

Is there a way to create a factor variable in R and simultaneously specify just the reference level for that factor?

I can accomplish this in two steps, first creating the factor, then using relevel(), e.g.

MyVar = factor(seq(1, 10))
MyVar = relevel(MyVar, ref = 5)

Or, I can do it in a single step, using the levels = argument of the factor() function. But, that requires first getting a list of all unique values of the factor and then putting the desired level first, which in turn will usually then require an additional couple of steps.

It seems like this should be a pretty basic functionality, but I can't seem to find a way to accomplish it. Is it just not possible directly in R?

Upvotes: 2

Views: 300

Answers (1)

akrun
akrun

Reputation: 887881

A flexible option would be to use fct_relevel from forcats where we can place the level anywhere

library(forcats)
fct_relevel(factor(seq(1, 10)), '5')
#[1] 1  2  3  4  5  6  7  8  9  10
#Levels: 5 1 2 3 4 6 7 8 9 10

Suppose, if the level should be after 2

fct_relevel(factor(seq(1, 10)), '5', after = 2)
#[1] 1  2  3  4  5  6  7  8  9  10
#Levels: 1 2 5 3 4 6 7 8 9 10

Also, as stated in the comments, it can be done in a single step with relevel as well

relevel(factor(seq(1, 10)), ref = 5)

Upvotes: 2

Related Questions