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

R语言中如何将price_range字段设置为4水平的factor?

实现方法

方法1:直接将数值型字段转为带指定标签的因子

如果price_range目前是数值类型(整数/小数),直接使用factor()函数指定原始水平和对应标签:

mobile_price_classification$price_range <- factor(
  mobile_price_classification$price_range,
  levels = c(0, 1, 2, 3),  # 原始字段的取值
  labels = c("poor", "Normal", "Medium", "High")  # 对应的新标签
)

方法2:修改已存在的因子水平

如果price_range已经是因子类型,可直接替换其水平标签(需确保原因子水平顺序为0,1,2,3):

levels(mobile_price_classification$price_range) <- c("poor", "Normal", "Medium", "High")

若原因子水平顺序不符,先重新指定水平再替换标签:

mobile_price_classification$price_range <- factor(
  mobile_price_classification$price_range,
  levels = c("0", "1", "2", "3"),  # 原因子的水平值(字符型)
  labels = c("poor", "Normal", "Medium", "High")
)

验证转换结果

执行以下命令确认转换是否成功:

# 查看字段结构
str(mobile_price_classification$price_range)
# 查看各水平的分布
table(mobile_price_classification$price_range)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 15:44:57