I have a factor in a data frame
with levels like hot
, warm
, tepid
, cold
, very cold
, freezing
. I want to map them to an integer column with values in the range [-2, 2]
for regression, with some values mapping to the same thing. I want to be able to specify the explicit mapping, so that very hot
words map to 2
, very cold
words to -2
, etc. How do I do this cleanly? I would love a function that I just pass some named list to, or something.
To convert factors to the numeric value in R, use the as. numeric() function. If the input is a vector, then use the factor() method to convert it into the factor and then use the as. numeric() method to convert the factor into numeric values.
There are two steps for converting factor to numeric: Step 1: Convert the data vector into a factor. The factor() command is used to create and modify factors in R. Step 2: The factor is converted into a numeric vector using as. numeric().
We can convert to numeric by using as. numeric() function. Example: R.
To convert a column to numeric in R, use the as. numeric() function. The as. numeric() is a built-in R function that returns a numeric value or converts any value to a numeric value.
Assume a factor vector x
holds the categories.
temperatures <- c("hot", "warm", "tepid", "cold", "very cold", "freezing")
set.seed(1)
x <- as.factor(sample(temperatures, 10, replace=TRUE))
x
[1] warm tepid cold freezing warm freezing freezing cold
[9] cold hot
Levels: cold freezing hot tepid warm
Create a numeric vector temp.map
with the mapping. Note that "hot" and "warm" map to the same value below.
temp.map <- c("hot"=2, "warm"=2, "tepid"=1, "cold"=0, "very cold"=-1, "freezing"=-1)
y <- temp.map[as.character(x)]
y
warm tepid cold freezing warm freezing freezing cold
2 1 0 -1 2 -1 -1 0
cold hot
0 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With