将分类变量转换为数字

时间:2017-02-19 01:45:39

标签: r

我有一个分类变量educa需要转换为数字以便于阅读。 educa可以承担6个值。我想将它们转换为1-6。我该怎么做呢?这不起作用:

brfs2013educationsummarycleaned <- 
    brfs2013educationsummary %>% 
    mutate(
    educa_level = ifelse(educa == "Never attended school or only kindergarten", 1, educat == "Grades 1 through 8 (Elementary)", 2, "not a real category"))

我做错了什么?以上是我打算做的一部分。

2 个答案:

答案 0 :(得分:0)

 as.numeric(educa)

会做你想要的,如果你想要它作为新列

 brfs2013educationsummarycleaned <- 
         brfs2013educationsummary %>% 
         mutate(educa_level = as.numeric(educa))

答案 1 :(得分:0)

如果'educa'中的值必须根据它们在数据中出现的顺序进行转换,我们可以使用match

library(tidyverse)
brfs2013educationsummary %>%
           mutate(educa_level = match(educa, unique(educa)))