Chapter 12 R Object - R Random Source

Add random feature tag to dependencies. All random functions are here https://docs.rustr.org/rustr/feature/random/struct.RRand.html.

use feature::random::*;
extern crate rand;
pub use rand::Rng;

// #[rustr_export]
pub fn gen_f64()->f64{
    let mut rrand = RRand::new();
    rrand.next_f64()
}
rust('
use feature::random::*;
extern crate rand;
pub use rand::Rng;
// #[rustr_export]
pub fn gen_f64()->f64{
    let mut rrand = RRand::new();
    rrand.next_f64()
}', depend = '

[dependencies]
rand = "0.3.14"

[dependencies.rustr]
version = "*"
features = ["random"]
'
)
#> updating cached Cargo.toml.

set.seed(10)

gen_f64()
#> [1] 0.631

set.seed(10)

gen_f64()
#> [1] 0.631

You can also use R internal function to generate random number, and remove rand crate dependency.

use feature::random::*;

// #[rustr_export]
pub fn runif_rand()->f64{
    let mut rrand = RRand::new();
    rrand.unif_rand()
}
rust('
use feature::random::*;

// #[rustr_export]
pub fn runif_rand()->f64{
    let mut rrand = RRand::new();
    rrand.unif_rand()
}', depend = '

[dependencies.rustr]
version = "*"
features = ["random"]
'
)
#> updating cached Cargo.toml.

set.seed(10)
runif_rand()
#> [1] 0.507

runif_rand()
#> [1] 0.307

set.seed(10)
runif_rand()
#> [1] 0.507

runif_rand()
#> [1] 0.307