imapply: Apply a function over an image

imapplyR Documentation

Apply a function over an image

Description

imapply() is a memory-efficient analogue of base::apply(). It gives the same answer, but where apply() permutes the whole array into a fresh copy before looping, imapply() gathers each sub-array directly through the stride vector. Peak memory is therefore the input plus the result, rather than twice the input plus the result, which matters once an image is larger than a comfortable fraction of memory.

Usage

imapply(x, margin, fun, ..., simplify = TRUE, threads = NULL, progress = FALSE)

voxelApply(
  x,
  fun,
  ...,
  mask = NULL,
  fill = 0,
  simplify = TRUE,
  threads = NULL,
  progress = FALSE
)

lineApply(
  x,
  fun,
  ...,
  axis = 1L,
  simplify = TRUE,
  threads = NULL,
  progress = FALSE
)

sliceApply(
  x,
  fun,
  ...,
  axis = 3L,
  simplify = TRUE,
  threads = NULL,
  progress = FALSE
)

Arguments

x

An image or a plain array.

margin

The dimensions to retain, as for base::apply().

fun

A function to apply.

...

Further arguments to fun.

simplify

Whether to simplify the result to an array where possible.

threads

Number of threads to use, or NULL to consult getOption("imply.threads"). See parallelism.

progress

FALSE for none, TRUE for a text progress bar showing the percentage complete and the rate in voxels per second, or a function of ⁠(done, total)⁠.

mask

For voxelApply(), a logical array over the spatial dimensions, a sparse image whose mask is to be used, or NULL for none. Locations outside it are not visited at all.

fill

The value given to locations outside mask.

axis

For lineApply(), the axis lines run along; for sliceApply(), the axis slices cut across.

Details

The remaining functions differ only in how much of the space they hand to fun at a time: a single location for voxelApply(), a one-dimensional line for lineApply(), and a two-dimensional slice for sliceApply().

In every case the values held at each location travel with the unit. So for an image with a time series at each location, voxelApply() passes one series, lineApply() passes a line's worth of series, and sliceApply() passes a slice's worth:

  dim(x) = 4 x 5 x 6 x 10, spatial = 3

  voxelApply(x, f)           f sees  10 values
  lineApply(x, f, axis = 1)  f sees  4 x 10
  sliceApply(x, f, axis = 3) f sees  4 x 5 x 10

axis always names a spatial dimension, but means what the name of each function implies: a line runs along its axis, whereas a slice is cut across its axis. Use imapply() directly to iterate over a non-spatial dimension, such as applying a function to each volume in a time series.

Value

For imapply(), as base::apply(). For voxelApply(), an image when the function returns a single value per location, otherwise an array.


imply documentation built on Sept. 15, 2026, 5:09 p.m.