如何调整 NumericVector 的大小? [英] How to resize a NumericVector?
问题描述
如何在 Rcpp 中调整 NumericVector
的大小?
How can I resize in Rcpp a NumericVector
?
当我为此使用 push_back
函数时,程序会变慢.但是没有 .resize()
或 .reserve()
函数.(当我已经有一个具有所需大小的 NumericVector
时,我可以使用复制构造函数来获取 NumericVector
的正确大小.在这种情况下,速度要快得多比使用 push_back
)
When I use the push_back
function for this, the Program slows down. But there are no .resize()
or .reserve()
functions.
(When I have already a NumericVector
with the desired size, I can use the copy-constructor to get the correct size of the NumericVector
. This is in such a case much faster than usage of push_back
)
推荐答案
如果您更喜欢 C++ 习惯用法,请使用 std::vector
并在将要转换的末尾返回它通过隐式 wrap()
到 R 向量.您还可以通过 RcppArmadillo 和 RcppEigen 使用 Armadillo 或 Eigen 向量.
If you prefer the C++ idioms, use std::vector<double>
and return that at the end where it will be converted via an implicit wrap()
to an R vector. You could also use Armadillo or Eigen vectors via RcppArmadillo and RcppEigen.
我们的对象是 R 对象的浅层包装,所以 push_back
对,比如说,Rcp::NumericVector
总是需要一个完整的副本.这是众所周知的并记录在案.
Our objects are shallow wrappers around the R object, so push_back
on, say, a Rcp::NumericVector
always needs a full copy. That is known and documented.
所以为了完整起见,这里是一个使用 RcppArmadillo 的例子:
So for completeness, here is an example using RcppArmadillo:
// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
// [[Rcpp::export]]
arma::vec shrink(arma::vec x) {
arma::vec y = x;
y.resize( y.size()-2 );
return y;
}
我们可以通过部署
R> Rcpp::sourceCpp('/tmp/vec.cpp')
R> shrink(1:10)
[,1]
[1,] 1
[2,] 2
[3,] 3
[4,] 4
[5,] 5
[6,] 6
[7,] 7
[8,] 8
R>
这篇关于如何调整 NumericVector 的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!