[R] read.table and factor

Prof Brian D Ripley ripley at stats.ox.ac.uk
Mon Feb 21 11:02:23 CET 2000


On Mon, 21 Feb 2000, Bill Simpson wrote:

> I have a data file like this:
> 
> std     cf      hit     miss    fa      cr
> 920     980     40      15      14      31
> 950     1010    24      23      23      30
> 1190    1250    26      21      27      26
> 1010    1070    33      10      28      29
> 1040    1100    35      10      11      44
> 
> I use read.table to read it in. My problem is that read.table makes std
> and cf into factors. I want them just to be ordinary numeric variables.
> 
> as.numeric(d$std) doesn't work properly (as the docs warn), and same goes
> for codes(d$std)

as.numeric(as.character(foo)), or if you really want to save space and 
have lots of repeated values

as.numeric(levels(foo))[as.numeric(foo)]

> How can I either tell read.table to leave the first two cols as numeric
> (not factors) or convert them from factors into the proper numeric values?

Well, in the example you give it does leave them as numeric if use
header=T. (You did do so, didn't you?)

> test <- read.table("test.dat", header=T)
> test
   std   cf hit miss fa cr
1  920  980  40   15 14 31
2  950 1010  24   23 23 30
3 1190 1250  26   21 27 26
4 1010 1070  33   10 28 29
5 1040 1100  35   10 11 44
> is.factor(test$std)
[1] FALSE

Maybe there is something else in the column that is not numeric. The
solution is to ensure that the column can be coerced to numeric without
errors.

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272860 (secr)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list