R语言课后作业

请使用switch()函数,编写一个函数dichot(),可以将一下随机产生的性别变量gender转换成0,1的虚拟变量。

set.seed(1)
n <- 5000
gender <- sample(c("f","m"),size=n,replace=TRUE)
提示:编写的函数应该如以下格式:

dichot <- function(x,type=c("f","m")){
...
return(newVar)

}

第1个回答  2015-10-29
dichot<-function(x,type=c("f","m")){
newVar<-as.numeric(x==type[2])
return(newVar)

}本回答被提问者和网友采纳