Re: [Rd] .Call ref card

From: Dirk Eddelbuettel <>
Date: Fri, 23 Mar 2012 12:21:45 -0500

Awesome. I love the reference card. This will be useful.

But I couldn't resist recasting your final "silly" example into

  1. inline use which I find generally easier than having to do R CMD SHLIB followed by dyn.load()
  2. a comparison with Rcpp which looks just about the same minus some UPPERCASE terms stemming from the R API.
     We turn error() into Rf_error() as that is a toggle Rcpp sets (given how
     error(), length(), etc conflict at times with things of the same name
     coming from somewhere else). Alternatively, we could also use 'throw
     std::range_error("invalid n")' which then calls Rf_error for us.

     It uses one templated cast to int, but the intent is as readable as
     asInteger. You could of course use asInteger too, as Doug eg prefers.

     It then declares on list type of the right size. Alloc and all that is
     done behind the scenes -- abstraction.  And the assignment of the
     unaltered SEXP type x that is prelicated may just be simpler. 

Code is below for both variants, and the same outputs.


R> library(inline)
R> replicateToListC <- cfunction(signature(x="any", N="integer"), body='

+ int n = asInteger(N);
+ if (n < 0) error("N must be non-negative");
+ SEXP res = allocVector(VECSXP, n);
+ for (int i = 0; i < n; i++) SET_VECTOR_ELT(res, i, x);
+ return res;

+ ')
R> replicateToListC(1:2, -2)
Error in replicateToListC(1:2, -2) : N must be non-negative R> replicateToListC(1:2, 2)
[1] 1 2

[1] 1 2

R> replicateToListCpp <- cxxfunction(signature(x="any", N="integer"), plugin="Rcpp", body='
+ int n = as<int>(N);
+ if (n < 0) Rf_error("N must be non-negative");
+ List res(n);
+ for (int i = 0; i < n; i++) res[i] = x;
+ return res;

+ ')
R> replicateToListCpp(1:2, -2)
Error in replicateToListCpp(1:2, -2) : N must be non-negative R> replicateToListCpp(1:2, 2)
[1] 1 2

[1] 1 2


"Outside of a dog, a book is a man's best friend. Inside of a dog, it is too
dark to read." -- Groucho Marx

______________________________________________ mailing list
Received on Fri 23 Mar 2012 - 17:29:53 GMT

This quarter's messages: by month, or sorted: [ by date ] [ by thread ] [ by subject ] [ by author ]

All messages

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Fri 23 Mar 2012 - 19:30:33 GMT.

Mailing list information is available at Please read the posting guide before posting to the list.

list of date sections of archive