[R] How to create as.numeric.xxx

Prof Brian Ripley ripley at stats.ox.ac.uk
Fri Nov 16 12:26:25 CET 2012


On 16/11/2012 10:01, Marc Girondot wrote:
> I would like to create a function to convert data based on a class using
> as.numeric
>
> Similarly, using a plot, I do:
> plot.essai <- function(x, ...) {return(x*2)}
> d <- 10
> class(d) <- "essai"
>
> plot(d)
>
> It works:
>
> [1] 20
> attr(,"class")
> [1] "essai"
>
> Now same with as.numeric:
> as.numeric.essai <- function(x, ...) {return(x*2)}
> as.numeric(d)

You need to read the help (as the posting guide asked you to do before 
posting):

      ‘as.numeric’ is a generic function, but S3 methods must be written
      for ‘as.double’.  It is identical to ‘as.double’ (and ‘as.real’).

The rest of the help page makes clear why using 'numeric' will confuse 
others as well as confusing yourself.

> It does not work:
>
> [1] 10
>
> Is it possible ?
>
> Thanks a lot
> Marc Girondot
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.


-- 
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 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list