bcapply

Apply a Function to 2 Broadcasted Arrays

Description

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

Usage

bcapply(x, y, f, v = NULL)

Arguments

x, y conformable atomic or recursive 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.
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, 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.

Value

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

Examples

library("broadcast")

x.dim <- c(c(10, 2,2))
x.len <- prod(x.dim)

gen <- function(n) sample(list(letters, month.abb, 1:10), n, TRUE)

x <- array(gen(10), x.dim)
y <- array(gen(10), c(10,1,1))

f <- function(x, y) list(x, y)
bcapply(x, y, f)
## , , 1
## 
##       [,1]   [,2]  
##  [1,] list,2 list,2
##  [2,] list,2 list,2
##  [3,] list,2 list,2
##  [4,] list,2 list,2
##  [5,] list,2 list,2
##  [6,] list,2 list,2
##  [7,] list,2 list,2
##  [8,] list,2 list,2
##  [9,] list,2 list,2
## [10,] list,2 list,2
## 
## , , 2
## 
##       [,1]   [,2]  
##  [1,] list,2 list,2
##  [2,] list,2 list,2
##  [3,] list,2 list,2
##  [4,] list,2 list,2
##  [5,] list,2 list,2
##  [6,] list,2 list,2
##  [7,] list,2 list,2
##  [8,] list,2 list,2
##  [9,] list,2 list,2
## [10,] list,2 list,2