如何在 Rcpp 中打印原始值
How to print raw values in 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 相同的方式打印 "raw" 类型的值。
可能吗?使用当前代码,我只得到一个空行。
您需要先将各个值转换为 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';
}
1 来自 Rbyte
, which is a typedef
for unsigned char
.
好吧,最简单 print-like-R 解决方案是调用 (C++) 函数 print()
,因为它在内部调度到 R 函数:
代码:
#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>
#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 相同的方式打印 "raw" 类型的值。 可能吗?使用当前代码,我只得到一个空行。
您需要先将各个值转换为 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';
}
1 来自 Rbyte
, which is a typedef
for unsigned char
.
好吧,最简单 print-like-R 解决方案是调用 (C++) 函数 print()
,因为它在内部调度到 R 函数:
代码:
#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>