-1

I would like to convert numbers into different categorical levels . For example,

In one of column of a dataframe, there are numbers: 1,2,3, 4. How can I cover them into "bottom", "middle", "high" , "top" in R codes?

Thanks, JL

JingJ
  • 5
  • 1
  • 6
  • 1
    Does this answer your question? [How to convert integer into categorical data in R?](https://stackoverflow.com/questions/16639484/how-to-convert-integer-into-categorical-data-in-r) – Samet Sökel Jun 12 '21 at 16:15
  • 1
    The answer does not address how to specify labels when converting to a factor. – dcarlson Jun 12 '21 at 16:32
  • I think a better duplicate target would be https://stackoverflow.com/q/36259842/5325862 – camille Jun 13 '21 at 20:32

1 Answers1

0

You can use factors (see ?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 
dcarlson
  • 10,936
  • 2
  • 15
  • 18
  • Thanks for your input. But How can we replace the number with the labels? – JingJ Jun 12 '21 at 16:20
  • I've added listings of `x` and `y`. It replaces the number with the label when printing, but uses the number internally. If you want to convert it to a character string use, `as.character(y)`, but you will loose the order which will become alphabetical (see `table(as.character(y)`). – dcarlson Jun 12 '21 at 16:29