r program changing yes/no variable to 1/0 - “ variable 'medal' is not a factor”

懵懂的女人 提交于 2019-12-25 18:53:25

问题


I am new to R. I have a categorical variable that I like to make a linear model and do prediction with it but RStudio does not let me do so unless I change the type of the variable. How can I change the yes/no to 1/0? my error is " variable 'medal' is not a factor" I have tried :

> sport$medal <- factor(sport$medal)
> is.factor(sport$medal)
[1] FALSE

回答1:


Apart from the obvious typo...

How can I change the yes/no to 0/1?

You need

sport$medal <- factor(sport$medal, levels = c("yes", "no"))

The default behaviour will give you 0 for "no" and 1 for "yes", as "n" comes ahead of "y" in alphabetical order.




回答2:


If you want to replace the yes/no with 1/0 use the ifelse()

sport$medal <- ifelse(sport$medal == "yes", 1, 0)


来源:https://stackoverflow.com/questions/38944567/r-program-changing-yes-no-variable-to-1-0-variable-medal-is-not-a-factor

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