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(1:5, c(5, 1, 1))

f <- function(x, y) strrep(x, y)
bcapply(x, y, f, v = "character")
## , , 1
## 
##      [,1]        [,2]              [,3]       
## [1,] "1"         "Jan"             "1"        
## [2,] "aa"        "11"              "aa"       
## [3,] "JanJanJan" "111"             "JanJanJan"
## [4,] "aaaa"      "1111"            "aaaa"     
## [5,] "11111"     "JanJanJanJanJan" "11111"    
## 
## , , 2
## 
##      [,1]              [,2]        [,3]             
## [1,] "Jan"             "1"         "Jan"            
## [2,] "11"              "aa"        "11"             
## [3,] "111"             "JanJanJan" "111"            
## [4,] "1111"            "aaaa"      "1111"           
## [5,] "JanJanJanJanJan" "11111"     "JanJanJanJanJan"