[R] How to create as.numeric.xxx

Rui Barradas ruipbarradas at sapo.pt
Fri Nov 16 12:21:29 CET 2012


Hello,

Actually, it's working as expected. 'numeric' is a class and the 
function as.numeric() is doing what it should:

as.numeric.essai <- function(x, ...) {return(x*2)}
d2 <- as.numeric(d)
class(d2)
[1] "numeric"

Maybe you want an as.essai function.

as.essai <- function(x, ...) {x <- as.numeric(x); class(x) <- "essai"; x*2}
as.essai(d)
[1] 20
attr(,"class")
[1] "essai"

I also think you're making a confusion about what the functions do. They 
coerce to a class, they don't do that sort of arithmetics.

Hope this helps,

Rui Barradas
Em 16-11-2012 10:01, Marc Girondot escreveu:
> 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)
>
> 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.




More information about the R-help mailing list