Public API for driving R from Elixir.

The external process backend is the default and production-preferred runtime. The embedded native backend is experimental and opt-in. Native Arrow dataframe exchange is available on validated native platforms, including macOS/arm64, when native is explicitly selected.

Summary

Functions

Returns the currently initialized backend, or nil when Rx has not been initialized.

Decodes a supported R object handle into Elixir data.

Serializes an R data frame object as Apache Arrow IPC stream bytes.

Encodes an Elixir value as a reusable R object handle.

Encodes an Elixir map with string keys as an R named list.

Ensures the default R backend is initialized without replacing an explicit backend init.

Evaluates R source code and returns the result handle plus global handles.

Initializes the configured R backend.

Captures base R plots produced by evaluating R source code.

Returns the text produced by R's print() method for an object.

Initializes the process backend with an explicit renv project environment.

Initializes the selected system R backend.

Selects and initializes the R backend for this BEAM.

Types

backend_selector()

@type backend_selector() ::
  :process | :port_arrow | :native | :embedded_nif | module()

global_value()

@type global_value() ::
  nil
  | boolean()
  | integer()
  | float()
  | String.t()
  | Rx.NA.t()
  | Rx.Object.t()
  | Rx.Table.t()
  | vector_value()
  | %{optional(String.t()) => global_value()}

globals()

@type globals() :: %{optional(String.t()) => global_value()}

vector_value()

@type vector_value() :: [boolean()] | [integer() | float()] | [String.t()]

Functions

backend()

@spec backend() :: :port_arrow | :native | module() | nil

Returns the currently initialized backend, or nil when Rx has not been initialized.

The value is :port_arrow for the external Rscript backend and :native for the embedded NIF backend.

decode(object)

@spec decode(Rx.Object.t()) :: term()

Decodes a supported R object handle into Elixir data.

Supported decoded values include nil, booleans, integers, floats, strings, flat atomic vectors, typed missing values as %Rx.NA{}, fully named plain R lists as maps, unnamed/partial/duplicate-name lists as %Rx.RList{}, and R table values as %Rx.Table{}. Opaque R objects, such as models and most classed objects, are returned as their original %Rx.Object{} handles.

decode_arrow(object)

@spec decode_arrow(Rx.Object.t() | term()) :: {:ok, binary()} | {:error, term()}

Serializes an R data frame object as Apache Arrow IPC stream bytes.

Returns {:ok, bytes} on success or {:error, reason} when the object is not an Arrow-compatible data frame or the R arrow package is unavailable.

encode!(object)

@spec encode!(global_value()) :: Rx.Object.t()

Encodes an Elixir value as a reusable R object handle.

Supported values are nil, booleans, integers in R's non-NA integer range, integers outside that range when exactly representable as an R double, floats, strings, flat homogeneous lists of booleans/numbers/strings, and string-key maps. Maps are encoded inline as R named lists; encode_list/1 exposes that map-only behavior explicitly.

Integer values outside the exact IEEE-754 double integer range are rejected instead of silently losing precision.

encode_list(map)

@spec encode_list(%{optional(String.t()) => global_value()}) :: Rx.Object.t()

Encodes an Elixir map with string keys as an R named list.

Returns a %Rx.Object{} that can be passed as an eval/3 global or decoded back to a map with decode/1. No R call is made — the map is stored inline in the object id and transmitted to R on first use.

Raises ArgumentError for non-string keys, unsupported value types, or Explorer.DataFrame values (use Rx.Explorer.to_r/1 first).

ensure_init()

@spec ensure_init() :: :ok

Ensures the default R backend is initialized without replacing an explicit backend init.

eval(source, globals, opts \\ [])

@spec eval(String.t(), globals(), keyword()) ::
  {Rx.Object.t() | nil, %{optional(String.t()) => Rx.Object.t()}}
  | Rx.EvalResult.t()

Evaluates R source code and returns the result handle plus global handles.

globals must be a map with string keys. Values may be raw scalar values (nil, booleans, finite numbers, and strings), %Rx.Object{} handles from prior calls, or string-key maps that are encoded as R named lists. Use encode!/1 when you need to pass a reusable vector handle.

By default this returns {result, globals} where result is a %Rx.Object{} or nil for empty/comment-only code, and globals contains %Rx.Object{} handles for variables left in the R evaluation environment.

With capture: true, this returns %Rx.EvalResult{} and captures stdout, messages, and warnings. In default mode, stdout is written to :stdout_device and messages/warnings are written to :stderr_device.

Options:

  • :capture - when true, return %Rx.EvalResult{}.
  • :stdout_device - IO device for stdout in default mode.
  • :stderr_device - IO device for messages and warnings in default mode.

R parse and evaluation errors raise Rx.Error.

init(opts \\ [])

@spec init(keyword()) :: :ok

Initializes the configured R backend.

Accepts the same options as system_init/1.

plot(source, globals, opts \\ [])

Captures base R plots produced by evaluating R source code.

The process backend opens a temporary PNG graphics device, evaluates the source, and returns every generated plot page in order. Low-level additions such as points() or lines() stay on the current page, matching normal R device behavior.

By default this returns a list of %Rx.Plot{} structs and routes stdout, messages, and warnings to the configured IO devices. With capture: true, it returns %Rx.PlotResult{} containing plots plus captured output.

Options:

  • :capture - when true, returns %Rx.PlotResult{} instead of plots
  • :format - plot format; only :png is supported initially
  • :width - PNG width in pixels, from 20 through 10000
  • :height - PNG height in pixels, from 20 through 10000
  • :res - PNG resolution, from 1 through 10000
  • :pointsize - PNG point size, from 1 through 1000
  • :max_pages - maximum captured plot pages, from 1 through 1000
  • :max_bytes - maximum total PNG bytes, from 1 through 2147483647
  • :stdout_device - IO device for stdout in default mode
  • :stderr_device - IO device for messages and warnings in default mode

Plot errors raise Rx.Error with captured output.

print(object, opts \\ [])

Returns the text produced by R's print() method for an object.

This is intended for opaque R objects such as fitted models, where the console-style display is useful but decode/1 should keep the object handle intact.

By default this returns stdout as a string. With capture: true, it returns a %Rx.PrintResult{} containing stdout, messages, and warnings.

Options:

  • :capture - when true, returns %Rx.PrintResult{} instead of stdout
  • :width - temporary R print width, from 10 through 10000
  • :max_print - temporary R max.print, from 1 through 2147483647

R print-method errors raise Rx.Error with captured output.

renv_init(project_or_lockfile, opts \\ [])

@spec renv_init(
  Path.t(),
  keyword()
) :: :ok

Initializes the process backend with an explicit renv project environment.

The first argument is either a project directory containing renv.lock or an explicit lockfile path. This function validates and loads the project environment only when called; ordinary Rx.init/1, Rx.ensure_init/0, and auto-init do not discover or activate renv projects.

system_init(opts \\ [])

@spec system_init(keyword()) :: :ok

Initializes the selected system R backend.

Options:

  • :backend - :process/:port_arrow for the external Rscript backend, or :native/:embedded_nif for the experimental NIF backend.
  • :r_binary - executable used by the process backend. Defaults to "Rscript".
  • :lib_paths - R library paths prepended to .libPaths().
  • :r_home - R home directory for the native backend.
  • :lib_r_path - path to libR.so or libR.dylib for the native backend.

system_init/1 is strict: after Rx is initialized, calling it with a different resolved backend configuration raises.

use_backend(backend, opts \\ [])

@spec use_backend(
  backend_selector(),
  keyword()
) :: :ok

Selects and initializes the R backend for this BEAM.

Calling use_backend/2 after the process backend has already initialized Rx stops that external R process and starts the newly selected backend. Existing backend-owned object handles from the stopped process are invalid after the switch.

The embedded native backend cannot currently be shut down inside the same BEAM. Once native has initialized, switching to another backend requires restarting the BEAM or Livebook runtime.

Supported selectors:

  • :process - external long-running Rscript process backend
  • :native - embedded NIF backend
  • :port_arrow - compatibility alias for :process
  • :embedded_nif - compatibility alias for :native

Options are the same as system_init/1, except the backend selector is passed as the first argument.