如何引用数字向量

How to cout NumericVectors?

本文关键字:数字 向量 引用 何引用      更新时间:2023-10-16

我对 Rcpp 编程很陌生,所以我正在尝试新的东西来了解一切是如何工作的。我写了一个小程序来比较两个 NumericVector 和 match() 函数。我还想打印出输入矢量和输出,但它似乎不起作用,因为我没有取回矢量的条目,而是存储位置(或类似的东西)。我还没有找到任何适用于数字矢量的"打印"功能,但也许还有另一种方法?任何帮助将不胜感激。

这是我的代码:

#include <Rcpp.h>
using namespace Rcpp;
using namespace std;
// [[Rcpp::export]]
IntegerVector vergl(NumericVector eins, NumericVector zwei){
 IntegerVector out = match(eins, zwei);
 cout << eins << endl;
 cout << zwei << endl;
 cout << match(eins, zwei) << endl;
 return out;
 }

一个小例子:

vergl(c(1,2,3),c(2,3,4))

输出:

> vergl(c(1,2,3),c(2,3,4))
0xa1923c0
0xa192408
0xb6d7038
[1] NA  1  2

谢谢。

Read gallery.rcpp.org/articles/using-rcout .

#include <RcppArmadillo.h>   
// [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;
// [[Rcpp::export]]
IntegerVector vergl(NumericVector eins, NumericVector zwei){
 IntegerVector out = match(eins, zwei);
 Rcout << as<arma::rowvec>(eins) << std::endl;
 Rcout << as<arma::rowvec>(zwei) << std::endl;
 Rcout << as<arma::rowvec>(out) << std::endl;
 return out;
}

在 R 中:

vergl(c(1,2,3),c(2,3,4))
#   1.0000   2.0000   3.0000
#
#   2.0000   3.0000   4.0000
#
#      nan   1.0000   2.0000
#
#[1] NA  1  2

请尝试此Rf_PrintValue(eins);Function print("print"); print(eins);或类似方法,如示例中的display函数所示。

例如,假设这是Rf_PrintValue.cpp:

#include <Rcpp.h>
using namespace Rcpp;
using namespace std;
// [[Rcpp::export]]
IntegerVector vergl(NumericVector eins, NumericVector zwei) {
 IntegerVector out = match(eins, zwei);
 Rf_PrintValue(eins);
 Rf_PrintValue(zwei);
 Rf_PrintValue(match(eins, zwei));
 Function print("print");
 print(out);
 Function display("display");
 display("out", out);
 return out;
}
/*** R
display <- function(name, x) { cat(name, ":n", sep = ""); print(x) }
vergl(c(1,2,3),c(2,3,4))
*/

我们可以像这样运行它。 前三个输出向量来自 Rf_PrintValue 语句,第四个来自 print 语句,第五个来自 display 函数,最后一个是 verg1 函数的输出:

> library(Rcpp)
> sourceCpp("Rf_PrintValue.cpp")
> display <- function(name, x) { cat(name, ":n", sep = ""); print(x) }
> vergl(c(1,2,3),c(2,3,4))
[1] 1 2 3
[1] 2 3 4
[1] NA  1  2
[1] NA  1  2
out:
[1] NA  1  2
[1] NA  1  2

已修订 更改了第二个解决方案并添加了一个示例。 还添加了display示例。