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

如何将R中字符型二元满意度列转换为因子型?

将字符型二元变量转换为因子型(R语言)

要把airline数据框中字符型的satisfaction列转换成你期望的因子格式,直接使用R的factor()函数即可,指定层级顺序能确保和你想要的结果完全匹配:

# 转换为因子型并指定层级顺序
airline$satisfaction <- factor(airline$satisfaction, 
                               levels = c("neutral or dissatisfied", "satisfied"))

验证转换结果

执行以下命令确认转换后的格式:

  • 用str(airline)查看列结构,会显示:
    $ satisfaction : Factor w/ 2 levels "neutral or dissatisfied", "satisfied": ...
    
  • 用summary(airline$satisfaction)会输出两个层级的样本数量统计,替代之前的字符型长度信息。

补充说明

如果不手动指定levels参数,R会默认按字母顺序对类别排序,这里"neutral or dissatisfied"的首字母在"satisfied"之前,所以默认结果也会符合你的要求,但显式指定层级能避免因数据中类别顺序变化导致的问题,更严谨。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 05:20:30