how to change gender factor into an numerical coding in r

前端 未结 2 894
旧巷少年郎
旧巷少年郎 2021-01-16 11:19

I have a factor of males and females say c(\"male\", \"female\",\"female\") and I want to create a vector of c(0,1,1) How can i change that in r?

2条回答
  •  失恋的感觉
    2021-01-16 12:13

    Maybe not the most straight-forward way, but I would first change it to a factor, and then, if needed to an integer:

    a <- c("male", "female","female")
    a <- factor(a, levels=c("male","female"), labels=c(0,1))
    a
    [1] 0 1 1
    Levels: 0 1
    
    as.integer(as.character(a)) #Need to be first transformed to a character 
    [1] 0 1 1                   #and then to an integer
    

提交回复
热议问题