简体   繁体   English

在 Rcpp 中将 arma:vec 转换为 NumericVector

[英]Convert arma:vec to NumericVector in Rcpp

I try to use the quantile function in RcppArmadillo, however, in the tutorial, the output of quantile function is arma::vec (The class of output in R is "matrix" "array").我尝试在 RcppArmadillo 中使用分位数 function,但是,在教程中,分位数 function 的 output 是 arma::vec(output 的 class in 8814664"82"arraytrix"")

quantile function in arma arma 中的分位数 function

I want to convert it to NumericVector.我想将它转换为 NumericVector。 I have tried with the codes following:我尝试使用以下代码:

#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;
using namespace arma;


// quantile function
// [[Rcpp::export]]
NumericVector quantile_f(vec V, vec P) {
  vec Q = quantile(V, P);
  NumericVector Q_output = as<NumericVector>(wrap(Q));
  return (Q_output);
}

I followed the link to do this.我点击了链接来执行此操作。 But I still get class in R = "matrix" "array".但我仍然在 R =“矩阵”“数组”中得到 class。

Output of my function in R Output 我的 function 在 R

Can anyone help with this?有人能帮忙吗? Thank!感谢!

(Please don't post images. Links to the documentation are preferred.) (请不要发布图片。首选文档链接。)

You don't need to convert it:你不需要转换它:

Code代码

// force return as a vector rather than single column matrix
#define RCPP_ARMADILLO_RETURN_ANYVEC_AS_VECTOR

#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]

// [[Rcpp::export]]
arma::vec quantile_f(arma::vec V, arma::vec P) {
    return arma::quantile(V, P);
}

/*** R
set.seed(123)
quantile_f(rnorm(1000), c(0, 0.25, 0.5, 0.75, 1.0))
*/

Output Output

> Rcpp::sourceCpp("~/git/stackoverflow/73979000/answer.cpp")

> set.seed(123)

> quantile_f(rnorm(1000), c(0, 0.25, 0.5, 0.75, 1.0))
[1] -2.80977468 -0.62874241  0.00920964  0.66478787  3.24103993
> 

Internally, of course, the equivalent conversion happens as the Armadillo vectors becomes the C++ variant of an R vector which is our Rcpp::NumericVector .当然,在内部,当 Armadillo 向量变成 R 向量(即我们的Rcpp::NumericVector )的 C++ 变体时,会发生等效转换。 But the existing code is nice enough to automate this for you.但是现有代码足以为您自动执行此操作。

Edit One can also explicitly reset the dimension attribute from an n by one matrix to a vector of length one: Edit One 还可以显式地将维度属性从 n × 1 矩阵重置为长度为 1 的向量:

// [[Rcpp::export]]
Rcpp::NumericVector quantile_f2(arma::vec V, arma::vec P) {
    arma::vec v = arma::quantile(V, P);
    Rcpp::NumericVector w = Rcpp::NumericVector(Rcpp::wrap(v));
    w.attr("dim") = static_cast<int>(v.n_elem);
    return w;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM