开发者

Convert Factor columns in data frame to numeric type columns [duplicate]

This question already has answers here开发者_StackOverflow: Closed 11 years ago.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜