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

3
  • 1
    stackoverflow.com/questions/4798343/convert-factor-to-integer Commented Jul 5, 2011 at 18:10
  • 2
    -1 for duplication. Suggest closing. It's also a FAQ and explicitly answered on the help page. Commented Jul 5, 2011 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. Commented Nov 17, 2014 at 15:42

3 Answers 3

9

You can use

as.numeric(as.character(x))
Sign up to request clarification or add additional context in comments.

Comments

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 = ",".

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.