如何在 Rcpp 中创建向量列表? [英] How do I create a list of vectors in Rcpp?
问题描述
我正在编写一个 Rcpp 模块,我想返回一个元素为向量的列表作为 RcppResultSet 列表的一个元素.例如,.Call("myfunc")$foo
应该是这样的:
I'm writing an Rcpp module an would like to return as one element of the RcppResultSet list a list whose elements are vectors. E.g., .Call("myfunc")$foo
should be something like:
[[1]]
[1] 1
[[2]]
[1] 1 1
[[3]]
[1] 1 1 1
(这里的确切数字并不重要).问题是我不知道这样做的正确 Rcpp 方式.我尝试传递一个 vector
但这通过默默地将第一个向量的长度作为宽度来构造一个矩阵(即使矩阵是参差不齐的!).我已经尝试构建一个 RcppList
,但很难将各种对象(如 RcppVector
)安全地投射到 SEXP
s 中.
(the exact numbers are not important here). The issue is that I don't know the right Rcpp way of doing this. I tried passing a vector<vector<int> >
but this constructs a matrix by silently taking the length of the first vector as the width (even if the matrix is ragged!). I've tried constructing an RcppList
but have a hard time casting various objects (like RcppVector
) safely into SEXP
s.
任何人都知道处理复杂结构(例如 Rcpp 中的向量列表)的最佳实践技巧?
Anyone have tips on best practices for dealing with complicated structures such as lists of vectors in Rcpp?
推荐答案
[ 很高兴在这里看到这个,但 Romain 和我通常推荐 rccp-devel 问题列表.请在那里发布,因为该项目还没有那么大,所以问题分散在整个网络上.]
[ Nice to see this here but Romain and I generally recommend the rccp-devel list for question. Please post there going forward as the project is not yet that large it warrants to have questions scattered all over the web. ]
RcppResultSet
是旧的经典 API 的一部分,而我们称之为新 API(从0.7.* 版本).看看当前的 CRAN 上的 Rcpp 页面 和小插曲列表——六个和数数.
RcppResultSet
is part of the older classic API whereas a lot of work has gone into what we call the new API (starting with the 0.7.* releases). Have a look at the current Rcpp page on CRAN and the list of vignettes -- six and counting.
使用新 API,您将返回类似
With new API you would return something like
return Rcpp::List::create(Rcpp::Named("vec") = someVector,
Rcpp::Named("lst") = someList,
Rcpp::Named("vec2") = someOtherVector);
全部在一个语句中(并且可能使用显式的 Rcpp::wrap()
调用),在 R 将是
all in one statement (and possibly using explicit Rcpp::wrap()
calls), creating what in R would be
list(vec=someVector, lst=someList, vec2=someOtherVector)
和 Rcpp::List
也应该能够做列表列表的列表......虽然我不确定我们是否有单元测试 --- 但有很多例子在500 多个单元测试.
And Rcpp::List
should also be able to do lists of lists of lists... though I am not sure we have unit tests for this --- but there are numerous examples in the 500+ unit tests.
碰巧的是,过去几天我花了很多时间转换RQuantLib 代码从经典 API 到新 API.一旦我们获得 Rcpp 的 0.8.3 版(希望在一个几天).同时,您可以查看 RQuantLibSVN存档
As it happens, I spent the last few days converting a lot of RQuantLib code from the classic API to the new API. This will probably get released once we get version 0.8.3 of Rcpp out (hopefully in a few days). In the meantime, you can look at the RQuantLib SVN archive
这篇关于如何在 Rcpp 中创建向量列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!