Chapter 8 R in Rust

It would be a good choice to read the document about Embedding R in the Writing R Extensions.

8.0.1 REngine

To initialize R inside of Rust:

let mut re =  unsafe { REngine::init().unwrap() };

To eval R script:

let res: f64 = re.eval("1+1").unwrap();
println!("{}", res);
assert_eq!(2.0, res);

To end the session of R:

re.leave();

REngine::init() can be called multiple times, but REngine::leave() can only be called one time.

8.0.2 Example

extern crate rustr;

use rustr::*;
use rustr::feature::engine::*;

fn main() {
    let mut re =  unsafe { REngine::init().unwrap() };
    
    let res: f64 = re.eval("1+1").unwrap();
    println!("{}", res);
    assert_eq!(2.0, res);

    unsafe{ re.leave() };
}

Cargo.toml adds engine feature tag:

[package]
name = "rustlib"
version = "0.1.0"

[dependencies.rustr]
features = ["engine"]

Run the binary on Linux and Mac:

export R_HOME=$(Rscript -e "cat(R.home())")

cargo run

Run the binary on Windows:

# set to RLIBPATH and PATH

set RLIBPATH="C:\Program Files\R\R-devel\bin\x64" 
set PATH=%PATH%;"C:\Program Files\R\R-devel\bin\x64"

cargo run