Learn R Programming

bitfield (version 1.0.0)

bf_decode: Decode (unpack) a bitfield

Description

This function takes an integer bitfield and the registry used to build it upstream to decode it into bit representation and thereby unpack the data stored in the bitfield.

Usage

bf_decode(x, registry, flags = NULL, envir = NULL, verbose = TRUE)

Value

Depending on the registry template type and envir parameter: If envir is NULL, returns a named list with decoded values for table templates, or a multi-layer SpatRaster for raster templates. If envir is specified, stores decoded flags as individual objects in that environment and returns invisible(NULL).

Arguments

x

integer table or raster of the bitfield. For registries with a SpatRaster template, x should be a SpatRaster. For registries with a data.frame template, x should be a data.frame.

registry

registry(1)
the registry that should be used to decode the bitfield.

flags

character(.)
the name(s) of flags to extract from this bitfield; leave at NULL to extract the full bitfield.

envir

environment(1)
optional environment to store decoded flags as individual objects. If NULL (default), returns results as a list or SpatRaster. Use .GlobalEnv to store flags directly in the workspace.

verbose

logical(1)
whether or not to print the registry legend.

Examples

Run this code
# build registry
reg <- bf_registry(name = "testBF", description = "test bitfield",
                   template = bf_tbl)
reg <- bf_map(protocol = "na", data = bf_tbl, registry = reg, x = commodity)
reg <- bf_map(protocol = "matches", data = bf_tbl, registry = reg,
              x = commodity, set = c("soybean", "maize"), na.val = FALSE)
reg

# encode the flags into a bitfield
field <- bf_encode(registry = reg)
field

# decode (somewhere downstream) - returns a named list
decoded <- bf_decode(x = field, registry = reg)
decoded$na_commodity
decoded$matches_commodity

# alternatively, store directly in global environment
bf_decode(x = field, registry = reg, envir = .GlobalEnv, verbose = FALSE)
na_commodity
matches_commodity

# with raster data
library(terra)
bf_rst <- rast(nrows = 3, ncols = 3, vals = bf_tbl$commodity, names = "commodity")
bf_rst$yield <- rast(nrows = 3, ncols = 3, vals = bf_tbl$yield)

reg <- bf_registry(name = "testBF", description = "raster bitfield",
                   template = bf_rst)
reg <- bf_map(protocol = "na", data = bf_rst, registry = reg, x = commodity)
field <- bf_encode(registry = reg)

# decode back to multi-layer raster
decoded <- bf_decode(x = field, registry = reg, verbose = FALSE)
decoded  # SpatRaster with one layer per flag

Run the code above in your browser using DataLab