Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convertic non-numeric factor to numeric column with mapping in R

Tags:

r

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.

like image 582
justinvf Avatar asked Jan 28 '13 06:01

justinvf


People also ask

How do I convert non numeric data to numeric in R?

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.

How do I recode factor to numeric in R?

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().

How do I change a character variable to a numeric in R?

We can convert to numeric by using as. numeric() function. Example: R.

How do you change a column value to numeric in 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.


1 Answers

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 
like image 89
Leo Avatar answered Sep 21 '22 21:09

Leo