Learn R Programming

broadcast (version 0.1.7)

bcapply: Apply Function to Pair of Arrays with Broadcasting

Description

The bcapply() method applies a function to 2 arrays element-wise with broadcasting.

Usage

bcapply(x, y, f, ...)

# S4 method for ANY bcapply(x, y, f, v = NULL)

Value

An atomic or recursive array with dimensions bc_dim(x, y).

Preserves some of the attributes of x and y similar to broadcasted infix operators, as explained in broadcast_operators.


Arguments

x, y

conformable atomic or recursive vectors/arrays.

f

a function that takes in exactly 2 arguments, and returns a result that can be stored in a single element of a recursive or atomic array.

...

further arguments passed to or from methods.

v

either NULL, or single string, giving the scalar type for a single iteration.
If NULL (default) or "list", the result will be a recursive array.
If it is certain that, for every iteration, f() always results in a single atomic scalar of exactly a specific type, the user can specify the type in v to pre-allocate the result.
Pre-allocating the results leads to slightly faster and more memory efficient code.
NOTE: Incorrectly specifying v leads to undefined behaviour;
when unsure, leave v at its default value.

Examples

Run this code


# check for each element in one recursive array if values are present in another:
mylist <- list(
  as.raw(0:255),
  sample(c(TRUE, FALSE, NA), 100, TRUE),
  0:255,
  rnorm(10),
  rnorm(10) + rnorm(10) * -1i,
  sample(month.abb)
)
mylist <- c(mylist, list(mylist))
x <- array(sample(mylist, 50, TRUE), c(5, 5, 2))
y <- array(sample(mylist, 50, TRUE), c(5, 5, 2))

bcapply(x, y, `%in%`) # returns a dimensional list / recursive array

bcapply(x, y, \(x, y) any(x %in% y), v = "logical") # returns logical array

bcapply(x, y, \(x, y) all(x %in% y), v = "logical") # returns logical array



# calculate quartiles for each list item, and return numeric array of quartiles:
x <- list(
  a = 1:10,
  beta = exp(-3:3),
  logic = c(TRUE,FALSE,FALSE,TRUE)
)
print(x)
quantiles <- array(c(1:3/4), c(1, 3))
colnames(quantiles) <- paste0("q = ", quantiles)
print(quantiles)

out <- bcapply(x, quantiles, \(x, y) quantile(x, probs = y), v = "double")
print(out)
typeof(out)

Run the code above in your browser using DataLab