Search code examples
rlistrcpp

List iteration crashes R


I'd like to do a list iteration in Rcpp, but this code crashes R:

Rcpp::cppFunction('List foo(List bc) {

              for (List::iterator i = bc.begin(); i != bc.end(); ++i) i[0] = i[1];

              return(bc);

            }'
)

If we take the following foo(list(a = c(1, 2, 3, 4), b = c(4, 3, 2, 1))), R will crash. The example above is just a dummy one - replace first element with second in every sublist (e.g. we should get c(2, 2, 3, 4) for a and for b c(3, 3, 2, 1)).

Could anyone help? I'm really new to both R and Rcpp and just going through the literature but have no idea about why the iterator doesn't work.


Solution

  • The problem is with i[0] and i[1]. Iterators are kinda-sorta-like pointers, you need to instantiate them first. Here is a variant of your code that works:

    Code

    #include <Rcpp.h>
    
    // [[Rcpp::export]]
    Rcpp::List foo(Rcpp::List bc) {
      for (Rcpp::List::iterator i = bc.begin(); i != bc.end(); ++i) {
        SEXP a = *i;
        Rcpp::print(a);
      }
    
      return(bc);
    }
    
    /*** R
    ll <- list(a = c(1, 2, 3, 4), b = c(4, 3, 2, 1))
    foo(ll)
    */
    

    Output

    edd@rob:~/git/stackoverflow/60291024(master)$ Rscript -e 'Rcpp::sourceCpp("question.cpp")'
    
    R> ll <- list(a = c(1, 2, 3, 4), b = c(4, 3, 2, 1))
    
    R> foo(ll)
    [1] 1 2 3 4
    [1] 4 3 2 1
    $a
    [1] 1 2 3 4
    
    $b
    [1] 4 3 2 1
    
    edd@rob:~/git/stackoverflow/60291024(master)$