如何将数字转换为分类值?

问题描述

我想将数字转换为不同的分类级别。例如,

在数据框的一列中,有数字:1,2,3,4。如何在 R 代码中将它们覆盖为“底部”、“中间”、“高”、“顶部”?>

谢谢, JL

解决方法

您可以使用因子(参见 ?factors):

set.seed(42)
x <- sample(4,15,replace=TRUE)
x
#  [1] 1 1 1 1 2 4 2 2 1 4 3 4 3 4 1
table(x)
# x
# 1 2 3 4 
# 6 3 2 4 
y <- factor(x,labels=c("bottom","middle","high","top"))
y
#  [1] bottom bottom bottom bottom middle top    middle middle bottom top    high   top    high   top    bottom
# Levels: bottom middle high top
table(y)
# y
# bottom middle   high    top 
#      6      3      2      4