Package 'zuarrow'

Title: Exact Conversion Between R Vectors and 'Apache Arrow' Columns
Description: Moves columns between R and the 'Apache Arrow' columnar format: the C data interface in memory and the inter-process communication (IPC) stream and file formats on disk. Every 'Arrow' type converts to an R vector and back, and a conversion either keeps every value unchanged or raises an error that names the column and the R type that would hold it exactly. A registry lets other packages declare which R class is the exact form of which 'Arrow' type. Handles share the layout of the 'nanoarrow' package, so objects pass between the two without conversion. The bundled 'nanoarrow' C library (<https://github.com/apache/arrow-nanoarrow>) needs no system library. The format is specified at <https://arrow.apache.org/docs/format/Columnar.html>.
Authors: Pedro Baltazar [aut, cre, cph], The Apache Software Foundation [cph] (nanoarrow, bundled in src/vendor/nanoarrow), Mikkel F. Jørgensen [cph] (flatcc runtime, bundled in src/vendor/nanoarrow), Paul Hsieh [cph] (pstdint.h in the bundled flatcc runtime)
Maintainer: Pedro Baltazar <[email protected]>
License: MIT + file LICENSE
Version: 0.1.0
Built: 2026-12-01 09:57:05 UTC
Source: https://github.com/pedrobtz/zuarrow

Help Index


Build an Arrow array or stream from R

Description

arrow_array() converts one R vector, or a data frame, to an array handle. arrow_stream() converts a data frame to a stream of record batches of at most batch rows each.

Usage

arrow_array(x, schema = NULL)

arrow_stream(x, batch = 65536L, schema = NULL)

Arguments

x

An R vector or a data frame.

schema

NULL, a format string or a schema handle.

batch

The largest number of rows in one batch, a positive whole number. Inf is a zuarrow_type_error.

Details

Without a schema, each R class maps to one Arrow type:

  • logical to bool, integer to int32, double to double.

  • character to utf8, or large_utf8 past 2^31 - 1 bytes.

  • factor to ⁠dictionary<int32, utf8>⁠. A factor with an NA level is a zuarrow_type_error, because a dictionary value cannot be null.

  • Date to date32, POSIXct to timestamp[us] in its time zone or UTC, difftime to duration[us].

  • A list of raw vectors to binary, or large_binary past 2^31 - 1 bytes. It goes to fixed_size_binary instead when it has the arrow_width attribute that arrow_to_r() gives one. An element of another length is then a zuarrow_type_error.

  • A list with the arrow_keys_sorted attribute that arrow_to_r() gives a map to map.

  • Any other list to ⁠list<T>⁠, with T from its elements.

  • A data frame to a struct.

A class registered with arrow_register() goes through its from handler. A matrix is written as a fixed_size_list with schema = arrow_matrix(), and only as a list type. A matrix with a class, such as a Date matrix, is a zuarrow_type_error. The attributes arrow_extension, arrow_extension_metadata and arrow_field_metadata become field metadata. Any other class is a zuarrow_type_error, and so is a tzone, units or arrow_extension_metadata attribute that R would not read as one value: one string, one of R's difftime units, one string or a raw vector.

Strings are written as UTF-8. A string in the native encoding that has no exact UTF-8 form, as any non-ASCII one in a C locale, is a zuarrow_type_error, and so is invalid UTF-8.

With a schema, the values are written as that type and checked: an integer that does not fit int8, or a double that is not a whole number for int64, is a zuarrow_lossy_error naming the row. POSIXct and difftime values are rounded to the schema's unit.

A character vector with an arrow_type attribute, as arrow_to_r() returns under lossy = "character", is written back as that type: each value is parsed, and text that is not the type's form, or holds more precision than the type, is an error. Only the canonical text that arrow_to_r() writes is read: other forms of the same value, such as "+1", "01", "-0" or "1" for a decimal of scale 2, are a zuarrow_lossy_error, and so is a time of day at or past 24:00:00. So the exact text round-trips, at the ends of the int64 range too.

Every NA becomes a null with a zeroed slot. NaN stays a value.

Value

arrow_array() returns an array handle; arrow_stream() a stream handle.

See Also

arrow_to_r() for the way back, arrow_types() for the table.

Examples

array <- arrow_array(c(1.5, NA, 3))
array
arrow_to_r(array)

stream <- arrow_stream(data.frame(x = 1:5), batch = 2)
as.data.frame(stream)

Compare two schemas, arrays or streams

Description

Two schemas are equal when their formats, names, flags and children match, and their metadata too unless metadata = FALSE. Two arrays are equal when their schemas are and they hold the same values, compared value by value: a null equals a null whatever bytes lie under it, and offsets do not matter. A dictionary or run-end encoded array compares by the values it decodes to. Two streams are equal when their schemas are and they yield the same number of batches, each pair equal. Comparing streams reads them both to the end.

Usage

arrow_equal(x, y, metadata = TRUE)

Arguments

x, y

Two handles of the same kind.

metadata

Whether schema and field metadata must match too.

Value

TRUE or FALSE. FALSE carries a reason attribute naming the first difference.

Examples

arrow_equal(arrow_schema("i"), arrow_schema("i"))
arrow_equal(arrow_schema("i"), arrow_schema("l"))

Limits on IPC input

Description

arrow_limits() bounds what arrow_read() accepts from untrusted input. Each limit is checked before the bytes it covers are used, and going over one is a zuarrow_limit_error.

Usage

arrow_limits(
  max_message = 2^31 - 1,
  max_depth = 64L,
  max_batch_rows = 2^31 - 1,
  max_bytes = Inf,
  max_dictionary = 2^28
)

Arguments

max_message

The most bytes one message header or body may hold, and the most bytes one compressed buffer may claim when decompressed.

max_depth

The deepest nesting a schema may have, counting a top-level column as one level. Whatever it says, a schema more than about 120 levels deep is a limit error, because the FlatBuffers verifier checks no deeper.

max_batch_rows

The most rows one record batch may hold.

max_bytes

The most bytes of input in all. For a list of sources, the most bytes of all of them together.

max_dictionary

The most bytes that delta dictionary batches may build in all. A delta onto a dictionary that holds values copies the whole dictionary into a new one, and every copy counts, so many small deltas cannot build a large amount of memory from a small input. A dictionary that deltas extend is also held to max_batch_rows values and max_message bytes. The default, 2^28 bytes (256 MiB), is far above what real deltas build and stops a hostile stream early.

Value

A list of class zuarrow_limits.

Examples

arrow_limits(max_bytes = 2^30)

Matrices as fixed-size lists

Description

arrow_matrix() asks for a matrix where a fixed_size_list is involved, in either direction. As the schema of arrow_array() it writes a matrix as a fixed_size_list with one list per row. As a prototype in the to of arrow_to_r() it reads a fixed_size_list column as a matrix with one row per list, NA rows for null lists. Without it, a fixed_size_list reads as a list column.

Usage

arrow_matrix()

Value

A marker object of class zuarrow_matrix.

Examples

m <- matrix(1:6, nrow = 2)
array <- arrow_array(m, schema = arrow_matrix())
array
arrow_to_r(array, to = arrow_matrix())

Schema metadata

Description

arrow_metadata() reads the custom metadata of a schema, or of the schema of an array or stream, as a named character vector. Values that are not valid UTF-8 or that contain a NUL byte are kept as raw vectors, and the result is then a named list.

Usage

arrow_metadata(x)

arrow_metadata(x) <- value

Arguments

x

A schema, array or stream handle. The replacement form takes a schema handle.

value

A named character vector, a named list of strings and raw vectors, or NULL.

Details

The replacement form returns a copy of the schema with new metadata: NULL removes it.

Value

A named character vector, or a named list when a value is binary. An empty named character vector when there is no metadata.

Examples

schema <- arrow_schema("i")
arrow_metadata(schema) <- c(origin = "zuarrow")
arrow_metadata(schema)

Read the Arrow IPC formats

Description

arrow_read() reads an Arrow IPC file, with its footer (.arrow, also called Feather version 2), or an IPC stream (.arrows). The framing is found from the first bytes, whatever the source is called.

Usage

arrow_read(
  x,
  columns = NULL,
  lazy = FALSE,
  to = NULL,
  lossy = zar_lossy_policies,
  limits = arrow_limits(),
  copy = TRUE
)

Arguments

x

A path, a raw vector, or a connection, which is read to its end. Or a list of these, each a whole IPC stream, read as one: Spark Connect, for one, sends each batch of a result as its own stream. Every stream must have the first one's schema, or it is a zuarrow_format_error. Every source in the list is read into memory when the call starts, and max_bytes binds all of them together.

columns

NULL for every column, or the names or positions of the top-level columns to read. Only those are decoded.

lazy

FALSE to read every batch into one data frame; TRUE to return a stream handle whose batches are decoded by arrow_next(), one at a time. For a list of sources the handle reads their batches in order, one stream after another. With lazy = TRUE, to, lossy and copy belong to that later conversion, and setting one here is a zuarrow_type_error.

to

NULL, or a named list of prototypes, one per column. For an array that is not a struct, a single prototype.

lossy

What to do with a column R cannot hold exactly.

limits

An arrow_limits() object.

copy

TRUE to create every R value during the conversion. FALSE to defer string columns: each becomes a character vector that keeps the Arrow buffers and creates an element's R string the first time it is used. Most of the cost of a string column is creating its R strings, so a result that is only partly read, or passed on, is much cheaper. The values are checked during the conversion either way, so copy = FALSE raises the same errors at the same time. The vector holds its own reference to the batch's memory until every element has been used, so releasing, moving or reusing x afterwards does not change it. To take that reference, x is turned in place into a reference-counted share of the same buffers. The vector is saved by saveRDS() as an ordinary character vector. Columns of other types, and strings read through a dictionary, a run-end encoding or a struct with nulls, are copied either way.

Details

The input is checked before it is used: every message is verified, every buffer must lie inside its message, and every limit of arrow_limits() binds, so malformed or hostile bytes are a zuarrow_format_error or a zuarrow_limit_error, never a crash. A file whose footer repeats the schema differently is a zuarrow_format_error too. Each batch then passes the full validation of arrow_validate() before it is converted. Bodies compressed with LZ4 or zstd are decompressed through 'zukomp'. Big-endian input is a zuarrow_format_error.

Dictionary batches, and the deltas a stream may send between record batches, are applied as the format says; a file that replaces a dictionary is an error, as the format forbids it. A delta extends a dictionary of fixed-width, binary or string values; a delta onto a dictionary of any other values is a zuarrow_format_error. Every column of a batch must hold the batch's number of rows.

A stream handle that has raised an error stays failed: every later arrow_next() raises the same error, so no batch is skipped or read against a dictionary that failed to arrive.

A raw vector is read where it is. With lazy = TRUE the handle holds a copy instead, because a handle can be passed to another consumer that outlives the vector.

Value

A data frame, or with lazy = TRUE a stream handle.

See Also

arrow_to_r() for the conversion and its lossy policy.

Examples

path <- tempfile(fileext = ".arrows")
df <- data.frame(x = 1:3, y = c("a", "b", "c"))
arrow_write(df, path, format = "stream")
arrow_read(path)

Register an exact R type for an Arrow type

Description

A typed package, such as 'zuint', 'decimal' or 'zutempo', tells zuarrow which R class is the exact form of an Arrow type. It does so in its .onLoad(), when zuarrow is installed; the registration lasts for the session and is removed when that package unloads.

Usage

arrow_register(
  key,
  to = NULL,
  from = NULL,
  class = NULL,
  package = NULL,
  exact = TRUE
)

arrow_unregister(key)

arrow_registry()

Arguments

key

A format string, a prefix pattern or an extension name.

to

NULL, or a function of ⁠(array, schema)⁠ or ⁠(array, schema, lossy)⁠ returning an R vector.

from

NULL, or a function of (x) returning an array handle.

class

The R classes from handles.

package

The registering package, so its registrations are removed when it unloads.

exact

Whether the conversion is exact.

Details

The key is one of:

  • an Arrow format string, matched exactly: "l" for int64;

  • a prefix pattern ending in * for parameterised types: "d:*" for every decimal, "tsn:*" for every nanosecond timestamp;

  • an extension name, such as "r.decimal".

When several keys match a column, the extension name wins, then the exact format string, then the pattern registered first. So a decimal128(38, 0) column is read by a "d:*" registration, even where it holds integers; naming a prototype of another registered class in the to of arrow_to_r() is how a caller opts into that class's handler instead. A package that registers a pattern again, as on a reload, keeps its place among the patterns; arrow_unregister() forgets it.

to converts Arrow to R: a function of ⁠(array, schema)⁠, the column's array and schema handles, returning an R vector of the array's length. It may be implemented in C against nanoarrow's r.h layout. It is called once per batch, and a piece of another length than its batch is a zuarrow_registry_error. Data frame pieces are combined column by column, and other pieces with c(). Where c() drops the class, the attributes the pieces share are kept, and pieces whose attributes differ are a zuarrow_registry_error. So a handler must give each batch a piece that combines into what one batch gives: a factor's levels, for instance, must not depend on the batch's values. A function of ⁠(array, schema, lossy)⁠ also receives the caller's lossy policy, so a handler can apply it to values its class cannot hold, such as one equal to its NA sentinel: an error under "error", NA with a warning under "warn". A to that cannot be called with two or three arguments is a zuarrow_registry_error.

from converts R to Arrow: a function of (x) returning an array handle of x's length, used for every object that inherits from class. It receives the whole column once, and the column's type is that array's, in arrow_schema() too. Batches are copies of that array's rows. An array of another length is a zuarrow_registry_error. Where several registrations' classes match an object, the one whose class comes first in class(x) is used, for from and for a prototype in the to of arrow_to_r().

Inside to, arrow_to_r() on the same column uses the built-in conversion, so a handler can start from it.

A registration declares whether it is exact. One that is not is used only under lossy = "warn" or "allow", and may not replace a type whose built-in conversion is exact. An extension is exact when its storage type is: an inexact registration for arrow.bool8, arrow.json or arrow.uuid is refused, and one that would read a column of exact storage is a zuarrow_registry_error. Registering a key again replaces the earlier registration, with a message naming both packages when another package owned it.

A dictionary or run-end encoded column is matched by its value type, not its index or run-end type, and to receives an array of its decoded values, one per row. Values of a fixed width, binary or string decode; any other layout is a zuarrow_type_error.

A union has no R form, but an extension over a dense_union or a sparse_union, such as geoarrow.geometry, can be registered. Its to receives the union array as nanoarrow lays it out: the type ids, a dense union's offsets and every child, whole. A sliced union keeps its offset, and the children are not sliced, as the Arrow format lays it out. Its null count is 0, since a union has no validity bitmap. With no handler for its extension name, a union column is a zuarrow_lossy_error.

Registered handlers apply to the top-level columns of a data frame and to the fields of nested data frames, at any depth, not to the items of a list column. A field under a null row of its data frame is NA.

Value

arrow_register() and arrow_unregister() return key invisibly. arrow_registry() returns a data frame with columns key, kind, class, package and exact.

Examples

arrow_register(
  "l",
  to = function(array, schema) arrow_to_r(array, to = character()),
  exact = TRUE
)
arrow_registry()
arrow_unregister("l")

Arrow schemas

Description

arrow_schema() makes a schema handle from a format string, from an R object, or from any schema, array or stream handle. A handle can come from zuarrow, from 'nanoarrow' or from any producer that uses its layout, such as 'arrow', 'duckdb' or an 'ADBC' driver.

Usage

arrow_schema(x)

Arguments

x

A format string, an R object, or a schema, array or stream handle.

Details

A single string is read as an Arrow format string, such as "i" for int32 or "tsu:UTC" for a microsecond timestamp in UTC. Any other R object gives the schema it would be written with: a data frame gives a struct with one field per column. On a handle, arrow_schema() never raises on the content: it returns a zuarrow schema handle as it is, copies any other schema, or asks a stream for it.

format() gives the type notation Arrow's own tools print, such as int64 or ⁠struct<x: int32>⁠, and print() shows it.

Value

A schema handle of class c("zuarrow_schema", "nanoarrow_schema").

See Also

arrow_metadata() for schema metadata, arrow_equal() to compare schemas.

Examples

arrow_schema("l")
arrow_schema(data.frame(x = 1:3, y = c("a", "b", "c")))
format(arrow_schema(as.Date("2026-10-21")))

Convert Arrow data to R

Description

arrow_to_r() converts an array to an R vector, and a stream or a struct array to a data frame with one column per field. The result carries no zuarrow class: it is a plain base R object.

Usage

arrow_to_r(x, to = NULL, lossy = zar_lossy_policies, copy = TRUE)

arrow_next(stream, to = NULL, lossy = zar_lossy_policies, copy = TRUE)

## S3 method for class 'zuarrow_array_stream'
as.data.frame(
  x,
  row.names = NULL,
  optional = FALSE,
  ...,
  to = NULL,
  lossy = zar_lossy_policies,
  copy = TRUE
)

## S3 method for class 'zuarrow_array'
as.data.frame(
  x,
  row.names = NULL,
  optional = FALSE,
  ...,
  to = NULL,
  lossy = zar_lossy_policies,
  copy = TRUE
)

## S3 method for class 'zuarrow_array'
as.vector(x, mode = "any")

Arguments

x

An array or stream handle.

to

NULL, or a named list of prototypes, one per column. For an array that is not a struct, a single prototype.

lossy

What to do with a column R cannot hold exactly.

copy

TRUE to create every R value during the conversion. FALSE to defer string columns: each becomes a character vector that keeps the Arrow buffers and creates an element's R string the first time it is used. Most of the cost of a string column is creating its R strings, so a result that is only partly read, or passed on, is much cheaper. The values are checked during the conversion either way, so copy = FALSE raises the same errors at the same time. The vector holds its own reference to the batch's memory until every element has been used, so releasing, moving or reusing x afterwards does not change it. To take that reference, x is turned in place into a reference-counted share of the same buffers. The vector is saved by saveRDS() as an ordinary character vector. Columns of other types, and strings read through a dictionary, a run-end encoding or a struct with nulls, are copied either way.

stream

A stream handle.

row.names

Must be NULL: the rows of a converted data frame have no names.

optional

Ignored. Column names always come from the schema.

...

Unused.

mode

Must be "any": the array converts to its own R form, as arrow_to_r() gives it, with the default lossy = "error".

Details

A conversion is exact or it fails. lossy decides what happens to a column that R cannot hold exactly, such as an int64 with a value past 2^53, a decimal128, or a nanosecond timestamp:

  • "error", the default, raises zuarrow_lossy_error, naming the column, the Arrow type, the first offending row where there is one, and the package that would read the column exactly.

  • "character" returns the values' exact text: integers as digits, decimals with their scale, timestamps in ISO 8601 at the type's precision. The column carries the Arrow format string in its arrow_type attribute.

  • "warn" converts to the nearest R type and raises one zuarrow_lossy_warning per column.

  • "allow" converts to the nearest R type silently. An int64 column becomes bit64's integer64, exactly, when bit64 is loaded.

Intervals and unions have no R form and always fail, unless a handler registered with arrow_register() for the column's extension name converts it.

Any other column with no values loses nothing, so it neither fails nor warns. Under "error" and "warn" it takes the form "allow" gives, so a query that reads only a table's schema converts under any policy.

to names the R type a column must become: character(), double(), integer(), or arrow_matrix() for a fixed_size_list. A target that cannot take the column is a zuarrow_type_error, never a silent fallback. A prototype of a class registered with arrow_register() converts the column through that registration's to handler, whatever its Arrow type.

Nested types follow the table too. A struct becomes a data frame column; list, large_list and the list views become list columns, NULL for a null list; a map becomes a list of data frames with columns key and value, and an arrow_keys_sorted attribute that writes it back as a map. A dictionary of strings becomes a factor, ordered when the dictionary is, with the union of every batch's levels; a dictionary of other values, and a run-end encoded array, decode to their values' R form. An extension type converts as its storage and keeps its name and metadata in the arrow_extension and arrow_extension_metadata attributes, so writing the column back restores it. Field metadata becomes the arrow_field_metadata attribute. A type registered with arrow_register() goes through its handler.

Value

An R vector, or a data frame.

arrow_next() returns the next batch as a data frame (or a vector, for a stream that is not of struct), or NULL once the stream has ended.

The as.data.frame() methods return a data frame. An array or stream that is not of struct is a zuarrow_type_error.

See Also

arrow_array() for the way there, arrow_types() for the table.

Examples

arrow_to_r(arrow_array(1:3))

big <- arrow_array(2^53 + 2, schema = "l")
try(arrow_to_r(big))
arrow_to_r(big, lossy = "character")

The built-in type table

Description

Lists every Arrow type zuarrow converts without a registration: its format string, its R form, whether that form is exact, the R form lossy = "allow" gives otherwise, and the package that reads it exactly.

Usage

arrow_types()

Value

A data frame of character columns: arrow, format, r, exact, lossy_r and exact_with. exact describes when the R form is exact, as text such as "yes", "no" or "within +/-2^53", not as a logical.

Examples

arrow_types()

Validate a handle

Description

Runs the 'nanoarrow' C library's validation on an array, or on every batch of a stream. A schema is only checked to be live.

Usage

arrow_validate(x, level = zar_validation_levels)

Arguments

x

A schema, array or stream handle.

level

The validation level.

Details

"minimal" checks buffer sizes, "default" also checks offsets and lengths, and "full" also reads buffer contents: offsets that only increase and dictionary indices in range, plus a check zuarrow adds that every non-null string is valid UTF-8. "full" is what zuarrow applies to every IPC input.

The C data interface records no buffer sizes, so no level can tell that a buffer is shorter than its array's length implies.

Validating a stream reads it to the end, so the stream is consumed.

Value

TRUE, invisibly. An invalid array raises zuarrow_format_error, with the path to the offending child in the message. A released handle raises zuarrow_handle_error.

Examples

arrow_validate(arrow_array(c("a", "b", NA)))
arrow_validate(arrow_stream(data.frame(x = 1:3)), level = "minimal")
arrow_validate(arrow_schema("i"))

Write the Arrow IPC formats

Description

arrow_write() writes a data frame, a struct array or a stream as an Arrow IPC file (format = "file", with a footer) or stream (format = "stream"). A path ending in .arrows defaults to the stream format; any other path, and x = NULL, to the file format.

Usage

arrow_write(
  data,
  x = NULL,
  format = zar_write_formats,
  compression = zar_codecs,
  level = NULL,
  batch = 65536L,
  dictionary = TRUE,
  metadata = NULL
)

Arguments

data

A data frame, a struct array handle or a stream handle.

x

NULL to return the bytes, a path, or a connection.

format

"file" or "stream".

compression

"none", "lz4" or "zstd".

level

NULL for the codec's default, or a level on its scale. A level that is not a whole number in R's integer range is a zuarrow_type_error, whatever the codec; one outside the codec's range is a zuarrow_codec_error.

batch

The most rows in one record batch, for a data frame.

dictionary

Whether factors are written as dictionaries.

metadata

NULL, or a named character vector of schema metadata.

Details

A data frame is split into record batches of at most batch rows. Each factor is written as a dictionary with one dictionary batch before the first record batch, or as plain strings with dictionary = FALSE. Columns with arrow_extension, arrow_extension_metadata or arrow_field_metadata attributes keep them as field metadata, and metadata becomes the schema's custom metadata.

Bodies are padded to 8 bytes with zeros and are uncompressed by default, so every reader opens the file. compression = "lz4" writes LZ4 frames and "zstd" zstd frames through 'zukomp', at level on the codec's own scale; a buffer that does not shrink is written as it is. The same input and options give the same bytes on every platform.

Value

A raw vector when x is NULL, otherwise x, invisibly.

See Also

arrow_read().

Examples

df <- data.frame(x = 1:3, f = factor(c("a", "b", "a")))
bytes <- arrow_write(df, NULL)
arrow_read(bytes)

path <- tempfile(fileext = ".arrows")
arrow_write(df, path, compression = "zstd")
arrow_read(path)

Package information

Description

Reports the versions zuarrow is built from: its own, the vendored 'nanoarrow' C library's, and the IPC metadata version it writes.

Usage

zuarrow_info()

Value

A named list with zuarrow, nanoarrow and ipc_metadata.

Examples

zuarrow_info()