how to change gender factor into an numerical coding in r

有些话、适合烂在心里 提交于 2019-12-30 11:55:36

问题


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?


回答1:


With boolean :

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

hth




回答2:


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


来源:https://stackoverflow.com/questions/19313862/how-to-change-gender-factor-into-an-numerical-coding-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!