[Rcpp-devel] Rcpp equivalent of sapply(L, length)
Dear Qiang, Thank you - that will do perfectly! And thanks also to Simon Urbanek for pointing out the R `lengths()` function which does the same on the R side. What great help in so little time. Thank you, colleagues! Greg.
On 2 Jul 2021, at 2:39, Qiang Kou wrote:
What about using "Rf_length"?
-------------------------------------------------------
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
IntegerVector c_listlengths(List L) {
IntegerVector lens(L.size());
for (int i=0; i<L.size(); i++) {
SEXP x = L[i];
lens(i) = Rf_length(x);
}
return lens;
}
----------------------------------------------------------
In R:
Rcpp::sourceCpp("example.cpp")
l=list(1:3, 2:3, 1:6)
l2=list(letters[1:3], letters[2:3], letters[1:6])
c_listlengths(l)
[1] 3 2 6
c_listlengths(l2)
[1] 3 2 6
l3=list(letters[1:6], letters[2:3], letters[1:3]) c_listlengths(l3)
[1] 6 2 3 On Thu, Jul 1, 2021 at 5:14 PM Dr Gregory Jefferis < jefferis at mrc-lmb.cam.ac.uk> wrote:
Dear RcppUsers, I feel like there must be a simple way to do the equivalent of sapply(L, length) in Rcpp but I can't seem to get past the problem of converting the elements of L into a type for which .size() or .length() are valid. I see that I could do this using some long switch(TYPEOF(x)) statement (eg https://gallery.rcpp.org/articles/rcpp-return-macros/): // [[Rcpp::export]] IntegerVector c_listlengths(List L) { IntegerVector lens(L.size()); for (int i=0; i<L.size(); i++) { SEXP x = L[i]; switch (TYPEOF(x)) { case INTSXP: { lens(i)=as<IntegerVector>(x).size(); } // handle other SXP types } } return lens; } but that that seems horribly convoluted. Can anyone point me to a simpler way? Apologies if this is an FAQ, but I did not yet manage to turn up anything close enough. With many thanks, Greg. # R example l=list(1:3, 2:3, 1:6) l2=list(letters[1:3], letters[2:3], letters[1:6]) sapply(l, length) sapply(l2, length) -- Gregory Jefferis Division of Neurobiology MRC Laboratory of Molecular Biology Francis Crick Avenue Cambridge Biomedical Campus Cambridge, CB2 OQH, UK http://www2.mrc-lmb.cam.ac.uk/group-leaders/h-to-m/g-jefferis http://jefferislab.org https://www.zoo.cam.ac.uk/research/groups/connectomics
_______________________________________________ Rcpp-devel mailing list Rcpp-devel at lists.r-forge.r-project.org https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel
-- Gregory Jefferis, PhD Tel: +44 1223 267048 Division of Neurobiology MRC Laboratory of Molecular Biology Francis Crick Avenue Cambridge Biomedical Campus Cambridge, CB2 0QH, UK http://www2.mrc-lmb.cam.ac.uk/group-leaders/h-to-m/g-jefferis http://jefferislab.org http://www.zoo.cam.ac.uk/research/groups/connectomics