1

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

    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
    ^
4

2 回答 2

2

我们可以使用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. 在这里,我将第一个和第三个更改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' 
              ))
于 2016-06-11T15:21:12.010 回答
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!

于 2016-06-11T17:51:29.377 回答