如何在Rcpp中打印原始值

时间:2018-07-04 09:12:34

标签: r rcpp

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
void print_raw(RawVector x) {

  for (int i = 0; i < x.size(); i++) {
    Rcout << x[i] << " ";
  }
  Rcout << std::endl;
}

/*** R
x <- as.raw(0:10)
print(x)
print_raw(x)
*/

我希望Rcpp以与R相同的方式打印“原始”类型的值。 可能吗?使用当前代码,我只会得到一个空白行。

2 个答案:

答案 0 :(得分:6)

您需要先将各个值强制转换为int 1 。此外,为了获得十六进制,零填充的输出,您需要使用<iomanip>函数。

使用范围-for循环,可以在循环变量的初始化中隐式地进行转换:

// [[Rcpp::export]]
void print_raw(RawVector x) {
  for (int v : x) {
    Rcout << std::hex << std::setw(2) << std::setfill('0') << v << ' ';
  }
  Rcout << '\n';
}

来自Rbytewhich is a typedef for unsigned char

1

答案 1 :(得分:4)

对于像print-R的最简单解决方案是在内部分配给R函数时调用(C ++)函数print()

代码:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
void print_raw(RawVector x) {
  print(x);
}

/*** R
x <- as.raw(0:10)
print(x)
print_raw(x)
*/

输出:

R> sourceCpp("/tmp/so51169994.cpp")

R> x <- as.raw(0:10)

R> print(x)
 [1] 00 01 02 03 04 05 06 07 08 09 0a

R> print_raw(x)
 [1] 00 01 02 03 04 05 06 07 08 09 0a
R>