[R] Simple numeric "as.is" question

Liaw, Andy andy_liaw at merck.com
Mon Mar 15 22:03:19 CET 2004


> From: Peter Dalgaard
> Sent: Monday, March 15, 2004 3:51 PM
> To: Timur Elzhov
> Cc: r-help at stat.math.ethz.ch; Janet Gannon
> Subject: Re: [R] Simple numeric "as.is" question
> 
> 
> Timur Elzhov <Timur.Elzhov at jinr.ru> writes:
> 
> > On Mon, Mar 15, 2004 at 09:04:05AM -0500, Janet Gannon wrote:
> > 
> > > I am reading a list of numbers from my clipboard, and have been 
> > > successful, except I can't make a histogram as R doesn't 
> recognize my 
> > > variable as numeric.  I know I need to use "as.is", but 
> the specifics 
> > > escape me. 
> > > 
> > > I have used x<-read.table("clipboard", header=F) to 
> import from a txt 
> > > file.  How do make this numeric?  Thanks, J.
> > 
> > x <- read.table("clipboard", header=F)
> > x <- as.data.frame(lapply(x, as.numeric))
> 
> This is almost always wrong. If a column was erroneously converted to
> a factor, it comes out as 1,2,3,4 even if the original values were
> 3.5,4,5.6,10.2. as.numeric(as.character(....)) is a better bet but a
> bit silly for those columns that were numeric to begin with.
> 
> You might try 
> 
> lapply(x,function(x) if (is.numeric(x)) x else
>         as.numeric(as.character(x)) )
> 
> but probably better is to find out *why* a variable is not read as
> numeric. It's usually because an least one value is not a number.

... which is why I suggested use scan() instead of read.table(), which
defaults to numeric input, and would complain about non-numeric input.

Re-reading the original message, there's really not enough info to tell
what's wrong.  How does Janet know that the data read in are not numeric?
What types were they exactly?  Are there more than one variable in the
input?

Andy

 
> -- 
>    O__  ---- Peter Dalgaard             Blegdamsvej 3  
>   c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
>  (*) \(*) -- University of Copenhagen   Denmark      Ph: 
> (+45) 35327918
> ~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: 
> (+45) 35327907
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! 
> http://www.R-project.org/posting-guide.html
> 
> 


------------------------------------------------------------------------------
Notice:  This e-mail message, together with any attachments,...{{dropped}}




More information about the R-help mailing list