簡體   English   中英

如何cout NumericVectors?

[英]How to cout NumericVectors?

我對使用Rcpp編程很新,所以我正在嘗試新的東西,看看一切是如何工作的。 我寫了一個小程序來比較兩個NumericVectors和match()函數。 我也想打印出輸入向量和輸出,但它似乎不起作用,因為我沒有得到向量的條目,但存儲位置(或類似的東西)。 我沒有為NumericVectors找到任何類型的“打印”功能,但也許還有另一種方法? 任何幫助將不勝感激。

這是我的代碼:

#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

謝謝。

試試這個Rf_PrintValue(eins); Function print("print"); print(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函數,last是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示例。

閱讀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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM