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 < jeffe...@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@lists.r-forge.r-project.org > https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel -- <https://nyquistdata.com/> <https://www.linkedin.com/company/nyquistdata/> <https://twitter.com/NyquistData>
_______________________________________________ Rcpp-devel mailing list Rcpp-devel@lists.r-forge.r-project.org https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel