This R statistical nmath re-created in typescript/javascript and handwritten webassembly.
Distributions:
beta, binomial, binomial-negative, cauchy, ch-2, exponential, fisher, gamma, geometric, hypergeometric (web assembly), logistic, log normal, multinomial, normal/gaussian, poisson distribution, singnrank (web assembly), student-t, tukey, uniform, weibull, wilcoxon.
Special functions:
bessel, beta, gamma, choose (the binomial coefficient $\binom{n}{k}$).
Pseudo Random genererators:
knuth-taocp, lecuyer-cmrg, marsalglia-multicarry, mersenne-twister, super-duper, wichman-hill, ahrens-dieter, box-muller, buggy-kinderman-ramage, inversion, kinderman-ramage.
This library has zero external dependencies.
This documentation assumes you knowledgable about the R build-in libaries.
npm i lib-r-math.js@latest # most recent stable version
Older documentation: - for the lts branch of version 2 see here - for the lts branch of version 1 see here.
If you were not using a previous version to 2.0.0, you can skip breaking changes and go to:
RNGkind function.The normal and uniform implementation of the various RNG's are not exported publicly anymore
Select normal and uniform RNG's via the function RNGkind.
// this is NOT possible anymore
import { AhrensDieter } from 'lib-r-math.js';
const ad = new AhrensDieter();
ad.random();
// NEW way of doing things
import { RNGkind, rnorm } from 'lib-r-math.js';
RNGkind({ normal: 'AHRENS_DIETER' }); // R analog to "RNGkind"
rnorm(8); // get 8 samples, if you only want one sample consider rnormOne()
Functions removed from 2.0.0 onwards: any, arrayrify, multiplex, each, flatten, c, map, selector, seq, summary.
It is recommended you either use well established js tools like Rxjs or Ramdajs to mangle arrays and data.
Functions removed from 2.0.0 onwards: numberPrecision
This function mimicked the R's options(digits=N).
Functions changed from 2.0.0 onwards: timeseed.
timeseed is now replaced by a cryptographic safe seed seed.
Float64Array.Functions changed from 2.0.0 onwards:
All these functions will return type of Float64Array:
rbeta, rbinom, rcauchy, rchisq, rexp, rf, rgamma, rgeom, rhyper, rlogis, rlnorm, rmultinom, rnorm, rpois, rsignrank, rt,runif, rweibull, rwilcox.
For single scalar (number) return values, use the analogs:
rbetaOne, rbinomOne, rcauchyOne, rchisqOne, rexpOne, rfOne, rgammaOne, rgeomOne, rhyperOne, rlogisOne, rlnormOne, rnormOne, rpoisOne, rsignrankOne, rtOne,runifOne, rweibullOne, rwilcoxOne.
Example:
import { rbinom, rbinomOne, setSeed } from 'lib-r-math.js';
rbinom(0); //
// -> FloatArray(0)
setSeed(123); // set.seed(123) in R
rbinom(2, 8, 0.5);
// -> Float64Array(2) [ 3, 5 ] //same result as in R
setSeed(456); // set.seed(456) in R
rbinomOne(350, 0.5);
// -> 174 ( a single scalar )
There is no UMD module from 2.0.0 onward.
Minimal version of node required is 22.12.0.
npm i lib-r-math.js
lib-r-math.js supports the following module types:
ObservableHQ works nicely with lib-r-math.js visualizing data generated by lib-r-math.js functions
Example: observableHQ-bessel-demo
Output As Graphic:

<script type="module">
import { BesselJ } from 'https://unpkg.dev/lib-r-math.js@latest/dist/web.esm.mjs';
console.log(BesselJ(3, 0.4));
//-> -0.30192051329163955
</script>
<script src="https://unpkg.dev/lib-r-math.js@latest/dist/web.iife.js"></script>
<script>
const answ = window.R.BesselJ(3, 0.4);
console.log(answ);
//-> -0.30192051329163955
</script>
import { BesselJ } from 'lib-r-math.js';
const answ = BesselJ(3, 0.4);
//-> -0.30192051329163955
const { BesselJ } = require('lib-r-math.js');
const answ = BesselJ(3, 0.4);
//-> -0.30192051329163955
RNGkindRNGkind is the analog to R's "RNGkind". This is how you select what RNG (normal and uniform) you use and the samplingKind (Rounding or Rejection) property
Follows closely the R implementation here
R console:
> RNGkind()
[1] "Mersenne-Twister" "Ahrens-Dieter"
[3] "Rejection"
Just like in R, calling RNGkind with no argument returns the currently active RNG's (uniform and normal) and sample kind (Rounding or Rejection)
Like in R, RNGkind optionally takes an argument of type RandomGenSet, after processing it will return the (adjusted) RandomGenSet indicating what RNG's and "kind of sampling" is being used.
Rjs typescript decl:
function RNGkind(options?: RandomGenSet): RandomGenSet;
Arguments:
options: an object of type RandomGenSetoptions.uniform: string, specify name of uniform RNG to use.options.normal: string, specify nam of normal RNG (shaper) to useoptions.sampleKind: string, specify sample strategy to useTypescript definition:
type RandomGenSet = {
uniform?:
| 'KNUTH_TAOCP'
| 'KNUTH_TAOCP2002'
| 'LECUYER_CMRG'
| 'MARSAGLIA_MULTICARRY'
| 'MERSENNE_TWISTER'
| 'SUPER_DUPER'
| 'WICHMANN_HILL';
normal?: 'AHRENS_DIETER' | 'BOX_MULLER' | 'BUGGY_KINDERMAN_RAMAGE' | 'KINDERMAN_RAMAGE' | 'INVERSION';
sampleKind?: 'ROUNDING' | 'REJECTION';
};
The RNGkind function is decorated with the following extra properties:
| property | description | example |
|---|---|---|
RNGkind.uniform |
list of constants of uniform RNG's | RNGkind.uniform.MARSAGLIA_MULTICARRY is equal to the string "MARSAGLIA_MULTICARRY" |
RNGkind.normal |
list of constants of normal RNG's | RNGkind.normal.KINDERMAN_RAMAGE is equal to the string "KINDERMAN_RAMAGE" |
RNGkind.sampleKind |
list of sampling strategies | RNGkind.sampleKind.ROUNDING is equal to the string "ROUNDING" |
Example: set uniform RNG to SUPER_DUPER and normal RNG to BOX_MULLER
import { RNGkind } from 'lib-r-math.js';
const uniform = RNGkind.uniform.SUPER_DUPER;
const normal = RNGkind.normal.BOX_MULLER;
RNGkind({ uniform, normal }); //-> "sampleKind" not specified so this will not be changed
RNGkind(); // no arguments, will return the current used RNG's and "sampleKind"
// returns
// {
// uniform: 'SUPER_DUPER',
// normal: 'BOX_MULLER',
// sampleKind: 'ROUNDING' // was not changed from default setting
// }
setSeedUses a single value to initialize the internal state of the currently selected uniform RNG.
R console analog: set.seed
Rjs typescript decl
function setSeed(s: number): void;
Arguments:
s is coerced to an unsigned 32 bit integerrandomSeedR console analog: .Random.seed
Rjs typescript decl
function randomSeed(internalState?: Uint32Array | Int32Array): Uint32Array | Int32Array | never;
Arguments:
internalState: the value of a previously saved RNG state, the current RNG state will be set to this.Exceptions:
internalState value is not correct for the RNG selected an Error will be thrown.All distribution functions follow a prefix pattern:
d (like dbeta, dgamma) are density functionsp (like pbeta, pgamma) are (cumulative) distribution functionq (like qbeta, qgamma) are quantile functionsr (like rbeta/rbetaOne, rgamma/rgammaOne) generates random deviates| type | function spec |
|---|---|
| density function | function dbeta(x: number, shape1: number, shape2: number, ncp?: number, log = false): number |
| distribution function | function pbeta(q: number, shape1: number, shape2: number, ncp?: number, lowerTail = true, logP = false): number |
| quantile function | function qbeta(p: number, shape1: number, shape2: number, ncp?: number, lowerTail = true, logP = false): number |
| random generation (bulk) | function rbeta(n: number, shape1: number, shape2: number, ncp?: number): Float32Array |
| random generation | function rbetaOne(shape1: number, shape2: number): number |
x, q: quantile valuep: probabilityn: number of observationsshape1, shape2: Shape parameters of the Beta distributionlog, logP: if true, probabilities are given as log(p).lowerTail: if true, probabilities are P[X ≤ x], otherwise, P[X > x].Example:
```j
$ claude mcp add libRmath.js \
-- python -m otcore.mcp_server <graph>