简体   繁体   中英

convert gender from character to numeric value in R

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?

我们可以用:

ms$Gender <- match(ms$Gender, c("Woman", "Man", "Non-binary"))

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
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM