Home > Net >  convert gender from character to numeric value in R
convert gender from character to numeric value in R

Time:07-18

I want to convert the character variable of gender into numeric. The structure of gender variable in character is like this:

$ Gender               : chr  "Woman" "Man" "Non-binary"

I have used this method to convert it to numeric:

ms$Gender[ms$Gender=='Woman']<- 1
ms$Gender[ms$Gender=="Man"]<-2
ms$Gender[ms$Gender=="Non-binary"]<-3

ms$Gender <- as.numeric(ms$Gender)

Is there any more efficient ways than this method?

CodePudding user response:

We can use case_when from the dplyr package:

ms$Gender <- case_when(
    ms$Gender == "Woman" ~ 1,
    ms$Gender == "Man" ~ 2,
    ms$Gender == "Non-binary" ~ 3
)

CodePudding user response:

We can use:

ms$Gender <- match(ms$Gender, c("Woman", "Man", "Non-binary"))
  •  Tags:  
  • r
  • Related