'R'中重新编码命令出错

时间:2016-06-11 15:10:30

标签: r recode

如何克服这个?非常感谢!使用'汽车'库

    data3$Edu=recode(data3$Edu, "'Incomplete secondary school: technical/ vocational type'=4")
Error in recode(data3$Edu, "'Incomplete secondary school: technical/ vocational type'=4") : 

  in recode term: 'Incomplete secondary school: technical/ vocational type'=4
  message: Error in parse(text = range[[1]][1]) : 
  <text>:1:1: unexpected INCOMPLETE_STRING
1: 'Incomplete secondary school
    ^

2 个答案:

答案 0 :(得分:1)

我们可以使用gsub删除这些特殊字符,然后执行recode

with(data3, recode(gsub("[/:]", "", Edu), 
     "'Incomplete secondary school technical vocational type' = 4"))

或者我们可以使用base R方法,例如将levels分配到新级别

levels(data3$Edu)[levels(data3$Edu)=="Incomplete secondary school: technical/ vocational type"] <- 4
data3
#               Edu
#1                4
#2   Something else
#3 Some other thing
#4                4

更新

由于OP希望将多个值重新编码为其他值,我们可以使用match。在这里,我将第1和第3 level更改为新值。

levels(data3$Edu)[match(levels(data3$Edu)[c(1,3)], levels(data3$Edu) ) ] <- c(4, 1)
data3
#               Edu
#1                4
#2                1
#3 Some other thing
#4                4

如果OP想要将所有级别更改为某些数值,我们可以直接将factor级别强制转换为数字

as.integer(data3$Edu)
#[1] 1 3 2 1

可以通过设置levels来改变值,即

as.integer(factor(data3$Edu, levels = levels(data3$Edu)[c(1,3,2)]))
#[1] 1 2 3 1

数据

data3 <- data.frame(Edu = c('Incomplete secondary school: technical/ vocational type', 
             'Something else',
             'Some other thing',
             'Incomplete secondary school: technical/ vocational type' 
              ))

答案 1 :(得分:0)

顺便说一句,谢天谢地@akrun我把他的建议和我的建议结合起来:

data1$Edu=as.factor(gsub("[/:]","",as.character(levels(data1$Edu))[data1$Edu]))
data1$Edu=as.numeric(recode(data1$Edu, "'No formal education'=1;
                 'Incomplete primary school'=2;
                 'Complete primary school'=3;
                 'Incomplete secondary school technical vocational type'=4;
                 'Complete secondary school technical vocational type'=5;
                 'Incomplete secondary school university-preparatory type'=6;
                 'Complete secondary school university-preparatory type'=7;
                 'Some university-level education, without degree'=8;
                 'University - level education, with degree'=9"))

希望它可以帮助某人。再次感谢@akrun!