3 bcast()
Inspired by the dot syntax from Julia’s broadcast()
function6, bcast()
/.()
allows the user to execute mapply()
with a convenient shorthand.
The function has two required inputs and two optional ones. The required arguments are f
, the function to call, and x
, the first argument over which to vectorize. The optional arguments are ...
, which is a list of additional arguments to the function, and simplify
, which defaults to FALSE
to maintain a list type in the output–when to set to TRUE
, the output is an array (typically a matrix a la` the mapply()
function).
3.0.1 Broadcasting with bcast()
# GOAL: Operate across multiple matrices.
a <- matrix(1:9, 3, 3)
b <- 20:22
c <- matrix(rnorm(9), 3)
bcast(`/`, a, b, simplify = TRUE) # matrix.
## [,1] [,2] [,3] [,4] [,5] [,6] [,7]
## [1,] 0.05000000 0.10000000 0.1500000 0.2000000 0.2500000 0.3000000 0.3500000
## [2,] 0.04761905 0.09523810 0.1428571 0.1904762 0.2380952 0.2857143 0.3333333
## [3,] 0.04545455 0.09090909 0.1363636 0.1818182 0.2272727 0.2727273 0.3181818
## [,8] [,9]
## [1,] 0.4000000 0.4500000
## [2,] 0.3809524 0.4285714
## [3,] 0.3636364 0.4090909
## Warning in mapply(f, x, y = dots, SIMPLIFY = simplify): longer argument not a
## multiple of length of shorter
## [[1]]
## [1] 0.05000000 0.04761905 0.04545455
##
## [[2]]
## [,1] [,2] [,3]
## [1,] -4.733159 -1.849731 2.228123
## [2,] -1.067596 -5.571419 5.494647
## [3,] -4.920125 291.250770 5.620815
##
## [[3]]
## [1] 0.1500000 0.1428571 0.1363636