how to change gender factor into an numerical coding in r

前端 未结 2 878
旧巷少年郎
旧巷少年郎 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 11:58

    With boolean :

    a <- c("male", "female","female")
    (a=="female")*1
    

    hth

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题