[Rcpp-devel] trying to insert a number as first element of already existing vector

Mark Leeds markleeds2 at gmail.com
Sun Dec 9 09:35:28 CET 2018


Hi All: I wrote below and it works but I have a strong feeling there's a
better way to do it. I looked on the net and found some material from back
in ~2014 about concatenating
vectors but I didn't see anything final about it. Thanks for any insights.

Also, the documentation for Rcpp is beyond incredible (thanks to dirk,
romain, kevin and all the other people I'm leaving out )  but is there a
general methodology for finding equivalents of R functions. For example, if
I want a cumsum function in Rcpp, how do I know whether to use the stl with
accumulate or if there's already one built in so
that I just call cumsum.

Thanks.

#=======================================================

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
std::vector<double> mybar(const std::vector<double>& x, double firstelem) {
  std::vector<double> tmp(x.size() + 1);
  tmp[0] = firstelem;
  for (int i = 1; i < (x.size()+1); i++)
    tmp[i] = x[i-1];
  return tmp;
}

/*** R

testvec = c(1,2,3)
testelem <- 7
mybar(testvec,testelem)

*/

#===============================
# OUTPUT FROM RUNNING ABOVE
#=================================
> testvec <-  c(1,2,3)
> testelem <- 7
> mybar(testvec,testelem)
[1] 7 1 2 3
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20181209/51028745/attachment.html>


More information about the Rcpp-devel mailing list