How to change the level of factor variable in R

#1

I want to change the level of my variable when I have created the a factor variable(x) and then I have unclass x I am getting 2 as yes and 1as no
x<-factor(c(“yes”,“no”,“yes”))

unclass(x)
[1] 2 1 2
attr(,“levels”)
[1] “no” "yes"
I want yes as 1 and no as 2

Why values are not changing using replacement function in R?
#2

hello @sid100158,

But this is a rather crude way of doing this.So if somebody could show a more efficient way of achieving the same it will be great.

#3

@sid100158-
x<-factor(c(“yes”,“no”,“yes”))
levels=c(“yes”,“no”)
x
[1] yes no yes
Levels: no yes

Hope this Helps!

#4
``````> x = factor(c("yes", "no", "yes"), levels = c("yes", "no"), labels = c(1, 2))
> x
[1] 1 2 1
Levels: 1 2``````

#5

You can do it using the relevel function. This makes ‘yes’ as the first level.

x=relevel(x,“yes”)

#6

levels(x) <- list(“yes” = “1”, “no” = “2”)
unclass(x)
[1] 1 2 1
attr(,“levels”)
[1] “yes” “no”

#7

Maybe the below helps:

x <- c(2,1,2)
factor_x<-factor(x)
levels(factor_x)
[1] “1” "2"
levels(factor_x) <- c(“No”, “Yes”)
factor_x
[1] Yes No Yes
Levels: No Yes