How to access elements of a vector in a Rcpp::List

前端 未结 1 2086
余生分开走
余生分开走 2021-02-14 07:47

I am puzzled.

The following compile and work fine:

#include 
using namespace Rcpp;
// [[Rcpp::export]]
List test(){
    List l;
    Integer         


        
相关标签:
1条回答
  • 2021-02-14 08:35

    It is because of this line:

    l[0][1] = 1;
    

    The compiler has no idea that l is a list of integer vectors. In essence l[0] gives you a SEXP (the generic type for all R objects), and SEXP is an opaque pointer to SEXPREC of which we don't have access to te definition (hence opaque). So when you do the [1], you attempt to get the second SEXPREC and so the opacity makes it impossible, and it is not what you wanted anyway.

    You have to be specific that you are extracting an IntegerVector, so you can do something like this:

    as<IntegerVector>(l[0])[1] = 1;
    

    or

    v[1] = 1 ;
    

    or

    IntegerVector x = l[0] ; x[1] = 1 ;
    

    All of these options work on the same underlying data structure.

    Alternatively, if you really wanted the syntax l[0][1] you could define your own data structure expressing "list of integer vectors". Here is a sketch:

    template <class T>
    class ListOf {
    public:
    
        ListOf( List data_) : data(data_){}
    
        T operator[](int i){
            return as<T>( data[i] ) ;
        }
        operator List(){ return data ; }
    
    private:
        List data ;
    } ;
    

    Which you can use, e.g. like this:

    // [[Rcpp::export]]
    List test2(){
        ListOf<IntegerVector> l = List::create( IntegerVector(5, NA_INTEGER) ) ; 
        l[0][1] = 1 ;
        return l;
    }
    

    Also note that using .push_back on Rcpp vectors (including lists) requires a complete copy of the list data, which can cause slow you down. Only use resizing functions when you don't have a choice.

    0 讨论(0)
提交回复
热议问题