11
$\begingroup$

I'd like to convert a factor variable to a numeric one but as.numeric doesn't have the effect I expect.

Below I get summary statistics for the numeric version of the variable based on the original variable. The means keep counting up by 1... perhaps (he speculates) the levels of the factor have both names and numbers, and I'm expecting the value of the new variable to come from the name when as.numeric is designed to use the number?

> describe.by(as.numeric(df$sch), df$sch)

group: 
  var    n mean sd median trimmed mad min max range skew kurtosis se
1   1 5389    1  0      1       1   0   1   1     0  NaN      NaN  0
--------------------------------------------------------- 
group: 001
  var  n mean sd median trimmed mad min max range skew kurtosis se
1   1 19    2  0      2       2   0   2   2     0  NaN      NaN  0
--------------------------------------------------------- 
group: 002
  var  n mean sd median trimmed mad min max range skew kurtosis se
1   1 54    3  0      3       3   0   3   3     0  NaN      NaN  0
--------------------------------------------------------- 
$\endgroup$
1
  • 1
    $\begingroup$ I removed the new tags you added; they seemed to me either too general and not discriminative, or in the case of as.factor too narrow (since it's a function in R base). Please retag if you think anything was lost. $\endgroup$
    – JMS
    Jul 15, 2011 at 6:13

2 Answers 2

30
$\begingroup$

That is correct: as.numeric(factor) returns the number that R assigns to the level of that factor. You could try as.numeric(as.character(factor))

$\endgroup$
2
  • 4
    $\begingroup$ As this answer suggests stackoverflow.com/a/3418192/476907 as.numeric(levels(f))[f] is recommended and slightly more efficient than as.numeric(as.character(f)) $\endgroup$
    – discipulus
    Jun 15, 2016 at 8:52
  • $\begingroup$ Thank you! This answer helped me a lot :) $\endgroup$
    – Yasha
    Jan 25, 2020 at 14:02
14
$\begingroup$

This is FAQ 7.10 in the R Frequently Asked Questions. Yes a factor is stored as the integers from 1 to the number of levels and as.numeric gives the underlying codes. The FAQ gives 2 ways to convert to numeric.

However, usually this is because when you read the data in there was something about your data that caused R to treat it as a factor instead of numbers (often a stray non-numeric character). It is often better to fix the raw data (the converting will convert the non-numeric piece to NA) or use the colClasses argument if using read.table or similar.

$\endgroup$
1
  • 1
    $\begingroup$ values.tmp <- sapply(possibleValues,as.numeric);values.nonnumeric <- values.tmp[is.na(values.tmp)] $\endgroup$ Jul 20, 2011 at 16:23

Not the answer you're looking for? Browse other questions tagged or ask your own question.