简体   繁体   English

如何使用“意外符号”错误重新编码R中的字符变量

[英]How to recode character variable in R with 'unexpected symbol' error

I want to recode my data from character to numeric. 我想将我的数据从字符重新编码为数字。 Here is my failed attempt: 这是我失败的尝试:

library(car) # needed for recode
survey1$V16a = recode(survey1$V16, "'Very important'=1; 'Fairly important'=2; 'Not very important'=3; 'Not important at all'=4; 'Can't choose'=99;", as.numeric.result=TRUE)

This is the error message I subsequently receive 这是我随后收到的错误消息

Error in recode(survey1$V16, "'Very important'=1; 'Fairly important'=2; 'Not very important'=3; 'Not important at all'=4; 'Can't choose'=99;", : 重新编码错误(survey1 $ V16,“非常重要'= 1;'非常重要'= 2;'不是很重要'= 3;'根本不重要'= 4;'不能选择'= 99;” ,:

in recode term: 'Can't choose'=99 message: Error in parse(text = strsplit(term, "=")[[1]][1]) : :1:7: unexpected symbol 1: 'Can't 在重新编码术语中:'不能选择'= 99消息:解析时出错(text = strsplit(term,“=”)[[1]] [1]):: 1:7:意外符号1:'可以' Ť

There's no real need to use an extra package such as car for this. 没有必要为此使用额外的包装,例如car It also makes the code less readable in my opinion. 在我看来,它也使代码的可读性降低。 Just use ifelse . 只需使用ifelse

survey1$V16a <- ifelse(survey1$V16a == "Very important", 1, 
                ifelse(survey1$V16a == "Fairly important", 2,
                ifelse(survey1$V16a == "Not very important", 3,
                .... )))))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM