bcapply

Apply Function to Pair of Arrays with Broadcasting

Description

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

Usage

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

## S4 method for signature 'ANY'
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.
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, 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(5, 3, 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(5, 1, 1))

f <- function(x, y) paste(x, y)
bcapply(x, y, f, v = "character")
## , , 1
## 
##      [,1]      [,2]    [,3]     
## [1,] "1 1"     "Jan 1" "1 1"    
## [2,] "Jan 1"   "Jan 1" "Jan 1"  
## [3,] "Jan a"   "Jan a" "Jan a"  
## [4,] "a Jan"   "a Jan" "a Jan"  
## [5,] "Jan Jan" "1 Jan" "Jan Jan"
## 
## , , 2
## 
##      [,1]    [,2]      [,3]   
## [1,] "Jan 1" "1 1"     "Jan 1"
## [2,] "Jan 1" "Jan 1"   "Jan 1"
## [3,] "Jan a" "Jan a"   "Jan a"
## [4,] "a Jan" "a Jan"   "a Jan"
## [5,] "1 Jan" "Jan Jan" "1 Jan"