#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.
You need to cast the individual values to int
1 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
.
Well the easiest solution to print-like-R is to call the (C++) function print()
as it dispatches to the R function internally:
#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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With