Convert Factor columns in data frame to numeric type columns
Possible Duplicates:
Convert factor to integer
R - How to convert a factor to an integernumeric 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
您可以使用
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
, eg 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).
上一篇: 从因子到数字或整数错误
下一篇: 将数据框中的因子列转换为数字类型列