Chapter 3 Data Exchange
If you want to exchange data between R and NodeJS, use an interchangeable format (JSON, arrow, base64 for images, raw strings…).
3.1 The hordes
R package
There is a hordes
R package that contains some functions to facilitate the data translation.
It can be installed with
3.2 JSON
Return
const {library} = require('hordes');
const jsonlite = library("jsonlite");
const base = library("base");
(async () => {
try {
const a = await jsonlite.toJSON("iris")
console.log(JSON.parse(a)[0])
} catch(e){
console.log(e)
}
}
)();
{
'Sepal.Length': 5.1,
'Sepal.Width': 3.5,
'Petal.Length': 1.4,
'Petal.Width': 0.2,
Species: 'setosa'
}
3.3 Text
By default, everything is returned as an array of string.
From the R side, it’s better to print things with cat
, as it allows to avoid the [1]
in front of the console printing.
## [1] 21
3.4 Base64 images
Given the following R function, contained in a package called {hordesx}
ggpoint <- function(n) {
gg <- ggplot(iris[1:n, ], aes(Sepal.Length, Sepal.Width)) +
geom_point()
hordes::base64_img_ggplot(gg)
}
const express = require('express');
const {library} = require('hordes');
const app = express();
const hordesx = library("hordesx")
app.get('/ggplot', async (req, res) => {
try {
const im = await hordesx.ggpoint(`n = ${req.query.n}`);
const img = Buffer.from(im, 'base64');
res.writeHead(200, {
'Content-Type': 'image/png',
'Content-Length': img.length
});
res.end(img);
} catch(e){
res.status(500).send(e)
}
})
app.listen(2811, function () {
console.log('Example app listening on port 2811!')
})
3.5 Files & Paths
// TODO
3.6 Arrow
// TODO
3.7 Stream
// TODO