将 std::vector 转换为 Rcpp 矩阵 [英] Convert std::vector to Rcpp matrix

查看:49
本文介绍了将 std::vector 转换为 Rcpp 矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个 Rcpp 转换相关的问题.我想将一个 long std::vector 转换为一个 Rcpp 矩阵对象,但想知道是否有一种简单的转换格式.自然地,您可以遍历每个元素并填充一个空的 Rcpp 矩阵,但这似乎很容易出错,如果有更方便的方法可能是不必要的.

This is an Rcpp conversion related Q. I'm looking to convert a long std::vector into a Rcpp matrix object, but want to know if there is an easy conversion format. Naturally, you could loop over each element and fill an empty Rcpp matrix, but this seems error prone and possibly needless if a more convenient approach is possible.

我问的原因是我想在一些现有的 C++ 代码中使用 OpenMP,但是将元素直接存储在 OpenMP 循环中的 Rcpp 矩阵对象中似乎效果不佳(而加载 std::vector对象并在 OpenMP 循环完成后转换为矩阵似乎是解决问题的好方法).

The reason I'm asking is I would like to utilize OpenMP in some existing C++ code, but storing element in the Rcpp matrix object directly in an OpenMP loop doesn't appear to work well (whereas loading a std::vector object and converting to a matrix after the OpenMP loop is complete seems to be a decent approach to the problem).

任何帮助将不胜感激!

推荐答案

您选择了一个好的方法.在 OpenMP 上下文中,您必须远离单线程 R.所以 std::vector 是好的.

You chose a good approach. In the OpenMP context, you have to stay away from the single-threaded R. So std::vector is good.

是的,我们有从 std::vectorRcpp::NumericVectorRcpp::NumericMatrix(毕竟是只是一个带有维度属性的向量)以及 Rcoo:Integer* 变体,以及通常的 as<>wrap转换器.

And yes, we have constructors from std::vector to Rcpp::NumericVector and Rcpp::NumericMatrix (which is after all just a vector with a dimensions attribute) as well as the Rcoo:Integer* variants, as well as the usual as<> and wrap converters.

Rcpp 单元测试、Rcpp 示例,当然还有 Rcpp Gallery 网站.

There should be plenty of examples in the Rcpp unit tests, the Rcpp examples, and of course on the Rcpp Gallery site.

这是一个过于简单的例子:

Here is an overly simple example:

 R> cppFunction('NumericVector phil(int n) { std::vector<double> x(n);
 +              return wrap(x); }') 
 R> phil(4)  
 [1] 0 0 0 0    
 R>    

这篇关于将 std::vector 转换为 Rcpp 矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆