Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print raw values in Rcpp

Tags:

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)
*/

I would like Rcpp to print values of type "raw" the same way as R does. Is it possible? With the current code, I get only a blank line.

like image 674
F. Privé Avatar asked Jul 04 '18 09:07

F. Privé


2 Answers

You need to cast the individual values to int1 first. Furthermore, in order to get the hexadecimal, zero-padded output you need to use <iomanip> functions.

Using a range-for loop, the conversion can happen implicitly in the initialisation of the loop variable:

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

1 from Rbyte, which is a typedef for unsigned char.

like image 52
Konrad Rudolph Avatar answered Oct 09 '22 04:10

Konrad Rudolph


Well the easiest solution to print-like-R is to call the (C++) function print() as it dispatches to the R function internally:

Code:

#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)
*/

Output:

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> 
like image 20
Dirk Eddelbuettel Avatar answered Oct 09 '22 04:10

Dirk Eddelbuettel