Search code examples
rrcpp

Rcpp: Storing elements to subset of vector


I'm still wrapping my head around Rcpp logic coming from an R context, so please be patient with me! From the following code:

Cjplus <- c(0,0)
Kseq <- c(1,2)
cand <- c(0,1)
cppFunction("NumericVector test(NumericVector Cjplus, NumericVector Kseq,
                   NumericVector cand, int i) {
  NumericVector A = as<NumericVector>(Cjplus[Kseq-1]);
  int B = cand[i-2];
  as<NumericVector>(Cjplus[Kseq-1]) = A + B;
  return Cjplus[Kseq-1];
}")
test(Cjplus, Kseq, cand, 3)

I expect to get [1] 1 1 as my output, but instead I get [1] 0 0. Am I indexing incorrectly here?


Solution

  • I don't understand why you try to use subset-assignment.

    Cjplus <- c(0,0)
    Kseq <- c(1,2)
    cand <- c(0,1)
    
    cppFunction("NumericVector test(NumericVector Cjplus, NumericVector Kseq,
                       NumericVector cand, int i) {
      NumericVector A = Cjplus[Kseq-1];
      double B = cand[i-2];
      A = A + B;
      return A;
    }")
    test(Cjplus, Kseq, cand, 3)
    #[1] 1 1
    

    Edit:

    Here is a version that does subset-assignment.

    library(Rcpp)
    cppFunction("NumericVector test(const NumericVector Cjplus, NumericVector Kseq,
                       NumericVector cand, int i) {
      NumericVector C = clone(Cjplus);
      NumericVector A = C[Kseq-1];
      double B = cand[i-2];
      A = A + B;
      C[Kseq-1] = A;
      return C;
    }")
    test(Cjplus, Kseq, cand, 3)
    #[1] 1 1