How to convert a factor that is represented by numeric values to integer or numeric
variable in R?


We can convert a factor to integer or numeric variable by using as.numeric function with defining the levels of the factor or by defining the characters of the factor

Example

> f <- factor(sample(runif(10), 10, replace = TRUE))
> f
[1] 0.323049098020419 0.916131897130981 0.271536672720686 0.462429489241913
[5] 0.657008627429605 0.462429489241913 0.462429489241913 0.212830029195175
[9] 0.271536672720686 0.497305172728375
7 Levels: 0.212830029195175 0.271536672720686 ... 0.916131897130981

Using as.numeric

> as.numeric(levels(f))[f]
[1] 0.3230491 0.9161319 0.2715367 0.4624295 0.6570086 0.4624295 0.4624295
[8] 0.2128300 0.2715367 0.4973052
> Using as.numeric(as.character( ))
> as.numeric(as.character(f))
[1] 0.3230491 0.9161319 0.2715367 0.4624295 0.6570086 0.4624295 0.4624295
[8] 0.2128300 0.2715367 0.4973052

Updated on: 06-Jul-2020

53 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements