[R] as(, "numeric") vs as.numeric()

Erik Wright eswright at wisc.edu
Mon Feb 1 16:00:45 CET 2016


Dear Frank,

Thank you for the quick response.

I am familiar with the tradeoffs between integers and doubles.  However, I do not believe this answers my question.

If you look at the help information for the as() function it says:  "as(x, "numeric") uses the existing as.numeric function."  But clearly the result is different in each case.

If the help for as() is correct, then as(1:10, "numeric") should also return doubles, and the second argument is not ignored.

Erik


> On Feb 1, 2016, at 8:16 AM, Franklin Bretschneider <bretschr at xs4all.nl> wrote:
> 
> Dear Erik Wright,
> 
> 
> Re:
> 
>> Could someone please explain this R behavior to me:
>> 
>>> typeof(as.numeric(1:10))
>> [1] "double"
>>> typeof(as(1:10, "numeric"))
>> [1] "integer"
>> 
>> I expected "double" in both cases.  In the help for the "as" function it says:
>> 
>> "Methods are pre-defined for coercing any object to one of the basic datatypes. For example, as(x, "numeric") uses the existing as.numeric function."
> 
> 
> This happens because 1:10 yields only integers, and so can be stored cheap,
> whereas as.numeric() actually means: as.double.
> The "numeric" in the second line is an unused argument.
> 
> Best regards,
> 
> Frank
> ---
> 
> 
> 
> 
> Franklin Bretschneider
> Dept of Biology
> Utrecht University
> bretschr at xs4all.nl
> 
> 
>



More information about the R-help mailing list