如何访问 Rcpp::List 中向量的元素 [英] How to access elements of a vector in a Rcpp::List
问题描述
我很困惑.
以下编译和工作正常:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
List test(){
List l;
IntegerVector v(5, NA_INTEGER);
l.push_back(v);
return l;
}
在 R 中:
R) test()
[[1]]
[1] NA NA NA NA NA
但是当我尝试在列表中设置 IntegerVector
时:
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;
}
它不编译:
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'
推荐答案
就是因为这一行:
l[0][1] = 1;
编译器不知道 l
是一个整数向量列表.本质上,l[0]
给了你一个 SEXP
(所有 R 对象的通用类型),而 SEXP
是一个指向 SEXPREC
其中我们无权访问 te 定义(因此不透明).因此,当您执行 [1]
时,您会尝试获得第二个 SEXPREC
,因此不透明度使其无法实现,无论如何这不是您想要的.
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.
你必须明确你正在提取一个IntegerVector
,所以你可以做这样的事情:
You have to be specific that you are extracting an IntegerVector
, so you can do something like this:
as<IntegerVector>(l[0])[1] = 1;
或
v[1] = 1 ;
或
IntegerVector x = l[0] ; x[1] = 1 ;
所有这些选项都适用于相同的底层数据结构.
All of these options work on the same underlying data structure.
或者,如果您真的想要语法 l[0][1]
,您可以定义自己的数据结构来表达整数向量列表".这是一个草图:
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;
}
另请注意,在 Rcpp
向量(包括列表)上使用 .push_back
需要列表数据的完整副本,这可能会导致速度变慢.仅当您别无选择时才使用调整大小功能.
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.
这篇关于如何访问 Rcpp::List 中向量的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!