Convert Factor columns in data frame to numeric type columns [duplicate]
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
You can use
as.numeric(as.character(x))
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 = ","
.
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).
精彩评论