将数字变量转换为有序因子的最佳方法

时间:2015-08-24 13:16:14

标签: r

我的数据框看起来像这样:

df1 <- data.frame(V1=rnorm(n = 100, mean=0, sd=1),
                  Edu=sample(x = c(-999,12,13,14,16,1), size = 100, 
                             replace = T, prob = c(0.05,0.2,.2,0.2,0.2,0.15)))

我想将变量Edu转换为有序因子变量。我可以使用以下代码将其转换为字符变量:

lutedu <- c('-999' = NA, '12' = "High School", '13' = "Associate's", 
         '14' = "Associate's", '16' = "Bachelor's", 
         '18' = "Master's, Graduate/professional", '21' = "PhD")

df1$Edu <- lutedu[as.character(df1$Edu)]

从那里我可以将字符变量转换为带ordered()的有序因子:

df1$Edu <-
  ordered(
    x = df1$Edu, levels = c(
      "High School", "Associate's", "Bachelor's",
      "Master's, Graduate/professional", "PhD"
    )
  )

有更好的方法吗?

1 个答案:

答案 0 :(得分:6)

不是使用命名向量进行重新编码,然后调用ordered,而是通过调用ordered并同时使用levelslabels参数来保存自己的步骤:

ordered(edu, levels=c(-999, 12, 13, 14, 16, 1),
        labels=c("NA", "High School", "Associate's", "Bachelor's",
                 "Master's/Graduate", "PhD"))
#   [1] High School       Master's/Graduate Master's/Graduate Bachelor's        Associate's      
#   [6] Master's/Graduate High School       Master's/Graduate High School       PhD              
# ...

数据

set.seed(144)
edu <- sample(x = c(-999,12,13,14,16,1), size = 100, 
              replace = T, prob = c(0.05,0.2,.2,0.2,0.2,0.15))