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

∥☆過路亽.° 提交于 2019-12-04 18:34:29

问题


I am puzzled.

The following compile and work fine:

#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
List test(){
    List l;
    IntegerVector v(5, NA_INTEGER);
    l.push_back(v);
    return l;
}

In R:

R) test()
[[1]]
[1] NA NA NA NA NA

But when I try to set the IntegerVector in the list:

// [[Rcpp::export]]
List test(){
    List l;
    IntegerVector v(5, NA_INTEGER);
    l.push_back(v);
    l[0][1] = 1;
    return l;
}

It does not compile:

test.cpp:121:8: error: invalid use of incomplete type 'struct SEXPREC'
C:/PROGRA~1/R/R-30~1.0/include/Rinternals.h:393:16: error: forward declaration of 'struct SEXPREC'

回答1:


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.



来源:https://stackoverflow.com/questions/17407762/how-to-access-elements-of-a-vector-in-a-rcpplist

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!