5

Possible Duplicates:
Convert factor to integer
R - How to convert a factor to an integer\numeric in R without a loss of information

I have read a text file where some of the columns with real number are read as factors into a data frame. How do i convert the factoe columns into numeric columns

Community
  • 1
  • 1
user597551
  • 979
  • 2
  • 9
  • 9
  • 1
    http://stackoverflow.com/questions/4798343/convert-factor-to-integer – Chase Jul 05 '11 at 18:10
  • 2
    -1 for duplication. Suggest closing. It's also a FAQ _and_ explicitly answered on the help page. – IRTFM Jul 05 '11 at 18:43
  • 4
    This is not a duplicate. This question targets at the problem of converting _all_ factor columns in a data frame automatically. The solution in the "duplicate" is not applicable: `as.numeric` does not work on data frames. – bluenote10 Nov 17 '14 at 15:42

3 Answers3

9

You can use

as.numeric(as.character(x))
EDi
  • 13,160
  • 2
  • 48
  • 57
1

The reason that your column with numbers got read in as a factor is that either there's something somewhere that makes the column not number-only or you've messed up the decimal character (this being the special case of the first problem). If your decimal is not ., you can specify a new one via argument dec, e.g. dec = ",".

Roman Luštrik
  • 69,533
  • 24
  • 154
  • 197
1

This is FAQ 7.10.

But rather than converting after the fact, why not read them in correctly by either specifying the colClasses argument if using read.table or one of its variants, or better yet, figuring out what character(s) in the file is(are) convincing R that your numbers are not all numbers and fixing the source file (or best, do both).

Greg Snow
  • 48,497
  • 6
  • 83
  • 110