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

R ProgrammingServer Side ProgrammingProgramming

<p>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</p><h2>Example</h2><pre class="prettyprint notranslate">&gt; f &lt;- factor(sample(runif(10), 10, replace = TRUE)) &gt; 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</pre><p>Using as.numeric</p><pre class="result notranslate">&gt; 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 &gt; Using as.numeric(as.character( )) &gt; 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</pre>
raja
Updated on 06-Jul-2020 12:43:51

Advertisements