[R] Coercing in R and in C (R-Extensions)

Duncan Murdoch murdoch.duncan at gmail.com
Tue May 31 20:15:41 CEST 2011


On 11-05-31 1:55 PM, Oliver wrote:
> Hello,
>
> in "Writing R Extensions" I found the following stuff:
>
>    "Note that these coercion functions are not the same as calling as.numeric
>     (and so on) in R code, as they do not dispatch on the class of the object.
>      Thus it is normally preferable to do the coercion in the calling R code."
>                   ( Writing R Extensions, 2011-04-13, page 100 )
>
> What is meant by this?

R has a complicated system of "classes" that is visible from C but not 
handled by default.  So for example, a numeric vector can be treated as 
a time by setting its class to c("POSIXct", "POSIXt").  (This is not the 
usual way to create time objects, but it would work.)

 > x <- 1:3
 > class(x) <- c("POSIXct", "POSIXt")
 > x
[1] "1969-12-31 19:00:01 EST" "1969-12-31 19:00:02 EST" "1969-12-31 
19:00:03 EST"

Now if you call as.character() in R, you'll get what is printed for x. 
But if you call asChar in C, you'll get the conversion of the numbers, 
i.e. "1", "2", "3".

>
> Maybe someone can explain me the problem in other words?
>
> What does coercion in R do, and what does coercion in C (not) do?
>
> (And what would be needed in C to get the same effect as in R?)

Check for a class, and dispatch on it if there is one.  Almost certainly 
you'd want to do this by building up an R expression and evaluating it.

Duncan Murdoch

>
>
> Thanks,
>     Oliver
>
> ______________________________________________
> 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