【问题标题】:How to recode character variable in R with 'unexpected symbol' error如何使用“意外符号”错误重新编码 R 中的字符变量
【发布时间】:2016-03-15 20:07:42
【问题描述】:

我想将我的数据从字符重新编码为数字。这是我失败的尝试:

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)

这是我随后收到的错误消息

重新编码错误(survey1$V16, "'非常重要'=1; '相当重要'=2; '不是很重要'=3; '一点也不重要'=4; '不能选择'= 99;", :

在重新编码术语中:'无法选择'=99 消息:解析错误(文本 = strsplit(术语,“=”)[[1]][1]): :1:7: 意外符号 1:'不能

【问题讨论】:

  • 尝试在Can\'t中将\放在'前面,这会让人困惑R
  • 始终指定您使用的软件包。 recode 来自 car
  • @TheRimalaya ,请作为答案发布...

标签: r r-car


【解决方案1】:

没有必要为此使用额外的包,例如car。在我看来,这也降低了代码的可读性。只需使用ifelse

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-12
    • 1970-01-01
    • 2018-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-27
    相关资源
    最近更新 更多