MCPcopy Index your code
hub / github.com/R-js/libRmath.js

github.com/R-js/libRmath.js @main

Chat with this repo
repository ↗ · DeepWiki ↗ · + Follow
529 symbols 2,451 edges 352 files 3 documented · 1%
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

libRmath.js

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.

Synopsys

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:

BREAKING CHANGES For version 2.0

Removed

RNG (normal and uniform) are only selectable via 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()

helper functions for data mangling

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.

Removed helper functions for limiting numeric precision

Functions removed from 2.0.0 onwards: numberPrecision

This function mimicked the R's options(digits=N).

Changed

helper functions

Functions changed from 2.0.0 onwards: timeseed.

timeseed is now replaced by a cryptographic safe seed seed.

Sample distributions return a result of type 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 )

UMD module removed

There is no UMD module from 2.0.0 onward.

Installation and usage

Minimal version of node required is 22.12.0.

npm i lib-r-math.js

lib-r-math.js supports the following module types:

ESM for use in observablehq

ObservableHQ works nicely with lib-r-math.js visualizing data generated by lib-r-math.js functions

Example: observableHQ-bessel-demo

Output As Graphic:

ESM for use as Browser client

<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>

IIFE (immediately-invoked Function Expression) for use in Browser client

<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>

ESM for Node

import { BesselJ } from 'lib-r-math.js';

const answ = BesselJ(3, 0.4);
//-> -0.30192051329163955

COMMONJS for node

const { BesselJ } = require('lib-r-math.js');

const answ = BesselJ(3, 0.4);
//-> -0.30192051329163955

Table of Contents

Auxiliary functions

RNGkind

RNGkind 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 RandomGenSet
    • options.uniform: string, specify name of uniform RNG to use.
    • options.normal: string, specify nam of normal RNG (shaper) to use
    • options.sampleKind: string, specify sample strategy to use

Typescript 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
//  }

setSeed

Uses 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 integer

randomSeed

R console analog: .Random.seed

Rjs typescript decl

function randomSeed(internalState?: Uint32Array | Int32Array): Uint32Array | Int32Array | never;

Arguments:

  • (optional) internalState: the value of a previously saved RNG state, the current RNG state will be set to this.
  • return state of the current selected RNG

Exceptions:

  • If the internalState value is not correct for the RNG selected an Error will be thrown.

Distributions

All distribution functions follow a prefix pattern:

  • d (like dbeta, dgamma) are density functions
  • p (like pbeta, pgamma) are (cumulative) distribution function
  • q (like qbeta, qgamma) are quantile functions
  • r (like rbeta/rbetaOne, rgamma/rgammaOne) generates random deviates

The Beta distribution

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
  • Arguments:
    • x, q: quantile value
    • p: probability
    • n: number of observations
    • shape1, shape2: Shape parameters of the Beta distribution
    • log, logP: if true, probabilities are given as log(p).
    • lowerTail: if true, probabilities are P[X ≤ x], otherwise, P[X > x].

Example:

```j

Extension points exported contracts — how you extend this code

Matchers (Interface)
(no doc)
src/packages/test-helpers/jest-ext.d.ts
ISummary (Interface)
(no doc)
src/lib/r-func.ts
JSObject (Interface)
(no doc)
scripts/nodeWalker.ts
DataView2 (Interface)
(no doc)
src/packages/test-helpers/jest-extension.ts
IBesselRC (Interface)
(no doc)
src/lib/special/bessel/IBesselRC.ts
IRandom (Interface)
(no doc)
src/lib/rng/IRandom.ts

Core symbols most depended-on inside this repo

toEqualFloatingPointBinary
called by 599
src/packages/test-helpers/jest-ext.d.ts
getStats
called by 158
src/packages/common/downstairs.ts
loadData
called by 131
src/packages/test-helpers/load.ts
random
called by 102
src/lib/rng/IRandom.ts
init
called by 83
src/lib/rng/knuth-taocp/index.ts
randoms
called by 69
src/lib/rng/IRandom.ts
createLogHarnas
called by 62
src/packages/common/downstairs.ts
globalUni
called by 58
src/lib/rng/global-rng.ts

Shape

Function 398
Method 84
Class 38
Interface 6
Enum 3

Languages

TypeScript100%

Modules by API surface

src/lib/r-func.ts40 symbols
src/lib/common/toms708/toms708.ts34 symbols
src/packages/test-helpers/jest-extension.ts20 symbols
src/lib/rng/knuth-taocp-2002/index.ts15 symbols
src/lib/rng/knuth-taocp/index.ts14 symbols
src/lib/distributions/gamma/pgamma.ts12 symbols
src/lib/rng/mersenne-twister/index.ts10 symbols
src/lib/rng/irng.ts10 symbols
src/lib/rng/__test__/test.ts10 symbols
src/packages/common/downstairs.ts9 symbols
src/lib/rng/normal/normal-rng.ts9 symbols
src/lib/rng/global-rng.ts9 symbols

For agents

$ claude mcp add libRmath.js \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact