You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言因子化含缩写的调查响应时语法错误的解决方法咨询

解决R中因子水平含单引号的语法错误

问题场景

在将赴约时间调查数据转为有序因子时,因因子水平里的I'm lucky to remember the appointment exists!包含单引号,而代码用单引号分隔水平字符串,导致R解析出错,报错信息如下:

Error: unexpected symbol in "factor_appointments <- factor(appointments, order = TRUE, levels =c('10 minutes early','5 minutes early','Precisely on time','A few minutes late','I'm"

下面是三种可行的解决方法:


方法1:用双引号包裹包含单引号的字符串

R允许混用单双引号定义字符串,用双引号包裹带单引号的内容,可避免解析冲突:

factor_appointments <- factor(appointments, order = TRUE, 
   levels =c('10 minutes early','5 minutes early',
   'Precisely on time','A few minutes late',
    "I'm lucky to remember the appointment exists!", ''))
factor_appointments
summary(factor_appointments)

方法2:转义字符串里的单引号

在单引号前加反斜杠\转义,明确告诉R这是字符串的一部分,而非结束标记:

factor_appointments <- factor(appointments, order = TRUE, 
   levels =c('10 minutes early','5 minutes early',
   'Precisely on time','A few minutes late',
    'I\'m lucky to remember the appointment exists!', ''))
factor_appointments
summary(factor_appointments)

方法3:使用R 4.0+支持的原始字符串

用r"(...)"格式包裹字符串,内部的单引号无需转义,写法更直观:

factor_appointments <- factor(appointments, order = TRUE, 
   levels =c('10 minutes early','5 minutes early',
   'Precisely on time','A few minutes late',
    r"(I'm lucky to remember the appointment exists!)", ''))
factor_appointments
summary(factor_appointments)

内容的提问来源于stack exchange,提问作者Cassandra Strand

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 10:43:17