我正打算按照要求here来读取R中c ++代码生成的一些二进制数据。我目前未使用Rcpp,并且已经研究了MsgPack article,但对继续采用该方法没有信心。是否有一种快速而肮脏的方法来读取以二进制格式编写的双精度或整数矩阵?
天真的用c ++编写一些二进制数据
std::ofstream doufile("double.dat", std::ios::out | std::ios::binary);
std::ofstream intfile("int.dat", std::ios::out | std::ios::binary);
//write ints
std::vector<int> a = {5, 10, -25, 29};
std::vector<std::vector<int>> b = {a, a, a};
for (int i = 0; i < b.size(); ++i)
intfile.write((char*)&b[i][0], a.size()*sizeof(int));
//write doubles
std::vector<double> c = {5.0, -10.2, 25.9, 29.3};
std::vector<std::vector<double>> d = {c,c,c};
doufile.precision(2);
for (int i = 0; i < d.size(); ++i)
doufile.write((char*)&d[i][0], c.size()*sizeof(double));
并在R中阅读
int <- readBin("int.dat", what=integer(), n=12, size=4, signed=TRUE, endian="little")
double <- readBin("double.dat", what=double(), n=12, size=4, signed=TRUE, endian="little")
print(int)
print(double)
收益
[1] 5 10 -25 29 5 10 -25 29 5 10 -25 29
[1] 0.000000e+00 2.312500e+00 2.720083e+23 -2.568750e+00 2.720083e+23
[6] 2.904687e+00 -1.073742e+08 2.957812e+00 0.000000e+00 2.312500e+00
[11] 2.720083e+23 -2.568750e+00
整数情况似乎还可以,但双打我在做什么呢?