[R] type conversion

Prof Brian Ripley ripley at stats.ox.ac.uk
Mon Mar 5 10:29:51 CET 2012

On 04/03/2012 22:26, Petr Savicky wrote:
> On Sun, Mar 04, 2012 at 03:18:33PM -0600, Matyas Sustik wrote:
>> Hi All,
>> I am confused by a type conversion happening against my intent.
>> In an R script I allocate a matrix X, and I pass it to a C function
>> by using
>> tmp -<  .C(..., as.double(X),...).
>> I use as.double() because I read that it makes sure that the
>> parameter passing is correct.
>> I return the matrix from the R script using:
>> return (list(..., X = tmp$X, ...))
>> The returned value is not a matrix but a flat vector.
>> I must not understand something fundamental that is happening
>> here.
> Hi.
> No, this is correct. See section 5.2 Interface functions .C and
> .Fortran in R-exts.pdf for the list of C types. There is int * and
> double *, which are vectors. Your R code should restore the dim
> attribute after the return from C code, for example using matrix()
> with appropriate nrow and ncol parameters.

'No, this is not correct'.  If you want to use a double matrix in .C or 
.Fortran, use

storage.mode(X) <- "double"

There are quite a few examples in R's own code, e.g. lm.fit.

> If you want to pass really a matrix, use .Call, which is more
> powerful.

But handling conversion in .Call is a lot trickier (especially if you 
want to dispatch methods), so e.g. det() uses storage.mode at R level 
before .Call.

> Hope this helps.
> Petr Savicky.
> ______________________________________________
> 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