[Rcpp-devel] Rcpp equivalent of sapply(L, length)

Dr Gregory Jefferis jefferis at mrc-lmb.cam.ac.uk
Fri Jul 2 02:13:44 CEST 2021


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


More information about the Rcpp-devel mailing list