bc_ifelse

Broadcasted Ifelse

Description

The bc_ifelse() function performs a broadcasted form of ifelse().

Usage

bc_ifelse(test, yes, no)

Arguments

test a vector or array, with the type logical, integer, or raw, and a length equal to prod(bc_dim(yes, no)).
If yes / no are of type raw, test is not allowed to contain any NAs.
yes, no conformable arrays of the same type.
All atomic types are supported.
Recursive arrays of type list are also supported.

Value

The output, here referred to as out, will be an array of the same type as yes and no.
If test has the same dimensions as bc_dim(yes, no), then out will also have the same dimnames as test.

After broadcasting yes against no, given any element index i, the following will hold for the output:

  • when test[i] == TRUE, out[i] is yes[i];

  • when test[i] == FALSE, out[i] is no[i];

  • when test[i] is NA, out[i] is NA when yes and no are atomic, and out[i] is list(NULL) when yes and no are recursive.

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))

cond <- bc.list(
  x, y,
  \(x, y)c(length(x) == length(y) && typeof(x) == typeof(y))
) |> as_bool()

bc_ifelse(cond, yes = x, no = y)
## , , 1
## 
##       [,1]         [,2]        
##  [1,] character,26 character,26
##  [2,] integer,10   integer,10  
##  [3,] integer,10   integer,10  
##  [4,] character,12 character,12
##  [5,] integer,10   integer,10  
##  [6,] character,26 character,26
##  [7,] integer,10   integer,10  
##  [8,] character,12 character,12
##  [9,] character,12 character,12
## [10,] character,26 character,26
## 
## , , 2
## 
##       [,1]         [,2]        
##  [1,] character,26 character,26
##  [2,] integer,10   integer,10  
##  [3,] integer,10   integer,10  
##  [4,] character,12 character,12
##  [5,] integer,10   integer,10  
##  [6,] character,26 character,26
##  [7,] integer,10   integer,10  
##  [8,] character,12 character,12
##  [9,] character,12 character,12
## [10,] character,26 character,26