JL,
There are many ways to do what you want. If you need to do it by yourself
using standard R, there are ways but if you are allowed to use packages,
like the forcats package in the tidyverse, it can be fairly simple. Here for
example is a way to convert a factor with the four levels you mention but
requires them to be character strings, so I converted it:
> library(forcats)
> orig <- factor(as.character(c(1:4, 4:1)))
> orig
[1] 1 2 3 4 4 3 2 1
Levels: 1 2 3 4> changed <- fct_recode(orig, bottom = "1", middle =
"2", high = "3", top "4")
> changed
[1] bottom middle high top top high middle bottom
Levels: bottom middle high top
The fct_recode line can also be used with explicit strings, needed if you
have things like embedded spaces:
changed <- fct_recode(orig,
"bottom" = "1",
"middle" = "2",
"high" = "3",
"top" = "4")
To make the changes yourself may require studying other things like how to
make substitutions using regular expressions.
-----Original Message-----
From: R-help <r-help-bounces at r-project.org> On Behalf Of Jxay Ljj
Sent: Saturday, June 12, 2021 11:25 AM
To: r-help at r-project.org
Subject: [R] covert categoral data into number
Hi
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
[[alternative HTML version deleted]]
______________________________________________
R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.